Given a string S, the task is to find the count of maximum occurring subsequence P from S using only those characters whose indexes are in Geometric Progression.
**Note: **Consider 1-based indexing in S.
**Examples : **
Input:_ S = “ddee”_
Output:_ 4_
Explanation:
If we take P = “de”, then P occurs 4 times in S. { {1, 3}, {1, 4}, {2, 3}, {2, 4} }
Input:_ S = “geeksforgeeks”_
Output:_ 6_
Explanation:
If we take P = “ek”, then P occurs 6 times in S. { {2, 4}, {3, 4}, {2, 12} {3, 12}, {10, 12}, {11, 12} }
Naive Approach: The idea is to generate all possible subsequences of the given string such that indexes of the string must be in geometric progression. Now for each subsequence generated, find the occurrence of each subsequence and print the maximum among those occurrences.
Time Complexity:_ O(2N)_
Auxiliary Space:_ O(1)_
Efficient Approach: The idea is to observe that any subsequence P can be of any length. Let’s say if P = “abc” and it occurs 10 times in S (where “abc” have their index in GP in S), then we can see that subsequence “ab” (having index in GP) will also occur 10 times in S. So, to simplify the solution, the possible length of P will be** less than equal **to 2. Below are the steps:
dp[i][j] = dp[i][j] + freq[i]
where,
freq[i] = frequency of character char(‘a’ + i)
dp[i][j] = frequency of string formed by current_character + char(‘a’ + i).
Below is the implementation of the above approach:
// C++ program for the above approach
#include <bits/stdc++.h>
**using**
**namespace**
std;
// Function to count maximum occurring
// subsequence using only those characters
// whose indexes are in GP
**int**
findMaxTimes(string S)
{
**long**
**long**
**int**
arr[26];
**long**
**long**
**int**
dp[26][26];
// Initialize 1-D array and 2-D
// dp array to 0
**memset**``(arr, 0,
**sizeof**``(arr));
**memset**``(dp, 0,
**sizeof**``(dp));
// Iterate till the length of
// the given string
**for**
(``**int**
i = 0; i < S.size(); i++) {
**int**
now = S[i] -
'a'``;
**for**
(``**int**
j = 0; j < 26; j++) {
dp[j][now] += arr[j];
}
arr[now]++;
}
**long**
**long**
**int**
ans = 0;
// Update ans for 1-length subsequence
**for**
(``**int**
i = 0; i < 26; i++)
ans = max(ans, arr[i]);
// Update ans for 2-length subsequence
**for**
(``**int**
i = 0; i < 26; i++) {
**for**
(``**int**
j = 0; j < 26; j++) {
ans = max(ans, dp[i][j]);
}
}
// Return the answer
**return**
ans;
}
// Driver Code
**int**
main()
{
// Given string s
string S =
"ddee"``;
// Function Call
cout << findMaxTimes(S);
**return**
0;
}
Output:
4
Time Complexity:_ O(max(N*26, 26 * 26))_
Auxiliary Space:_ O(26 * 26)_
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
#dynamic programming #mathematical #strings #algorithms-dynamic programming #frequency-counting #geometric progression #subsequence