Maximize length of subsequence consisting of single distinct character possible by K increments in a string
Given a string S consisting of lowercase characters and an integer K, the task is to find the maximum length of a subsequence consisting of a single distinct character possible by incrementing at most K characters.
Input: S = “acscbcca” K = 1
Explanation: Incrementing the character S from ‘b’ to ‘c’, modifies the string to “acscccca”. Therefore, longest subsequence of same characters is “ccccc”. Length of the subsequence is 5.
Input: S = “adscassr”, K = 2
- Initialize the variables, say start, end, and sum to 0 that stores the starting and ending indexes of the subsequences the sum of the sliding window.
- Initialize a variable, say ans to INT_MIN that stores the length of the resultant longest subsequence.
- Sort the given string S.
- Traverse the string over the range [0, N – 1] and perform the following steps:
- Increment the value of the sum by the value (S[end] – ‘a’).
- Iterate a loop until the value of (sum + K) is less than (S[end] – ‘a’) * (end – start + 1) and perform the following steps:
- Decrement the value of the sum by (S[start] – ‘a’).
- Increment the value of the start by 1.
- After the above steps, all the characters over the range [start, end] can be made equal by using at most K increments. Therefore, update the value of ans as the maximum of ans and (end – start + 1).
- After completing the above steps, print the value of ans as the result.
Below is the implementation of the above approach:
Time Complexity: O(N * log N)
Auxiliary Space: O(1)
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.