Maximize length of subsequence consisting of single distinct character possible by K increments in a string | C ++ program for the above approach ; Function to find the maximum length of a subsequence of same characters after at most K increment operations ; Store the size of S ; Sort the given string ; Stores the maximum length and the sum of the sliding window ; Traverse the string S ; Add the current character to the window ; Decrease the window size ; Update the value of sum ; Increment the value of start ; Update the maximum window size ; Print the resultant maximum length of the subsequence ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxSubsequenceLen ( string S , int K ) { int N = S . length ( ) ; int start = 0 , end = 0 ; sort ( S . begin ( ) , S . end ( ) ) ; int ans = INT_MIN , sum = 0 ; for ( end = 0 ; end < N ; end ++ ) { sum = sum + ( S [ end ] - ' a ' ) ; while ( sum + K < ( S [ end ] - ' a ' ) * ( end - start + 1 ) ) { sum = sum - ( S [ start ] - ' a ' ) ; start ++ ; } ans = max ( ans , end - start + 1 ) ; } cout << ans ; } int main ( ) { string S = " acscbcca " ; int K = 1 ; maxSubsequenceLen ( S , K ) ; return 0 ; }