Maximize length of subsequence consisting of single distinct character possible by K increments in a string | Java 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 sort ( S . begin ( ) , S . end ( ) ) ; convert input string to char array ; sort tempArray ; 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
import java . io . * ; import java . math . * ; import java . util . Arrays ; class GFG { static void maxSubsequenceLen ( String s , int K ) { int N = s . length ( ) ; int start = 0 , end = 0 ; char S [ ] = s . toCharArray ( ) ; Arrays . sort ( S ) ; int ans = Integer . MIN_VALUE , 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 = Math . max ( ans , end - start + 1 ) ; } System . out . println ( ans ) ; } public static void main ( String args [ ] ) { String S = " acscbcca " ; int K = 1 ; maxSubsequenceLen ( S , K ) ; } }