Length of longest subsequence whose difference between maximum and minimum ASCII value of characters is exactly one | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumLengthSubsequence ( string str ) { unordered_map < char , int > mp ; for ( char ch : str ) { mp [ ch ] ++ ; } int ans = 0 ; for ( char ch : str ) { if ( mp . count ( ch - 1 ) ) { int curr_max = mp [ ch ] + mp [ ch - 1 ] ; ans = max ( ans , curr_max ) ; } } cout << ans ; } int main ( ) { string S = " acbbebcg " ; maximumLengthSubsequence ( S ) ; return 0 ; }