Maximize count of occurrences of S2 in S1 as a subsequence by concatenating N1 and N2 times respectively
Given two strings S1, S2 of length N and M respectively, and two positive integers N1 and N2, the task is to find the maximum count of non-overlapping subsequences of S1 which are equal to S2 by concatenating the string s1, n1 times and the string s2, n2 times.
Input: S1 = “acb”, S2 = “ab”, N1 = 4, N2 = 2
Concatenating the string S1, N1 ( = 4) times modifies S1 to “acbacbacbacb”.
Concatenating the string S2, N2 ( = 2) times modifies S2 to “abab”.
Since the string S2 occurs twice as a non-overlapping subsequence in S1, the required output is 2.
Input: S1 = “abc”, S2 = “a”, N1 = 1, N2 = 1
Approach: The problem can be solved using the concept of checking if a string is a subsequence of another string or not.
Follow the steps below to solve the problem:
- Iterate over the characters of the string S2 and check if all the characters of S2 are present in the string S1 or not. If found to be false, then no such subsequence of S1 is possible which can be made equal to S2 by concatenating the string S1, N1 times and the string S2, N2 times.
- Iterate over the characters of the string S1, N1 times circularly. For every ith index, check if any subsequence of S1 exists up to ith index, which is equal to S2 or not. If found to be true, then increment the count.
- Finally, print the count obtained divided by N2 as the required answer, after performing the above operations.
Below is the implementation of the above approach:
Time Complexity: O((N + M) * n1)