Length of longest subsequence whose difference between maximum and minimum ASCII value of characters is exactly one | Java program for the above approach ; Function to find the maximum length of subsequence having difference of ASCII value of longest and smallest character as 1 ; Stores frequency of characters ; Iterate over characters of the string ; Stores the resultant length of subsequence ; Check if there exists any elements with ASCII value one less than character ch ; Size of current subsequence ; Update the value of ans ; Print the resultant count ; Driver Code
import java . util . * ; class GFG { static void maximumLengthSubsequence ( String str ) { HashMap < Character , Integer > mp = new HashMap < > ( ) ; for ( char ch : str . toCharArray ( ) ) { mp . put ( ch , mp . getOrDefault ( ch , 0 ) + 1 ) ; } int ans = 0 ; for ( char ch : str . toCharArray ( ) ) { if ( mp . containsKey ( ( char ) ( ch - 1 ) ) ) { int curr_max = mp . get ( ch ) + mp . get ( ( char ) ( ch - 1 ) ) ; ans = Math . max ( ans , curr_max ) ; } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String S = " acbbebcg " ; maximumLengthSubsequence ( S ) ; } }