![]() |
VOOZH | about |
Given a string str of lowercase English alphabets, our task is to find the frequency of occurrence a subsequence of the string which occurs the maximum times.
Examples:
Input: s = "aba"
Output: 2
Explanation:
For "aba", subsequence "ab" occurs maximum times in subsequence 'ab' and 'aba'.Input: s = "acbab"
Output: 3
Explanation:
For "acbab", "ab" occurs 3 times which is the maximum.
Approach: The problem can be solved using Dynamic Programming. To solve the problem mentioned above the key observation is that the resultant subsequence will be of length 1 or 2 because frequency of any subsequence of length > 2 will be lower than the subsequence of length 1 or 2 as they are also present in higher length subsequences. So we need to check for the subsequence of length 1 or 2 only. 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:
3
Time Complexity: O(26*N), where N is the length of the given string.
Auxiliary Space: O(M), where M = 26*26