Wednesday, 27 Oct 2021

# Length of longest subsequence whose difference between maximum and minimum ASCII value of characters is exactly one

Length of longest subsequence whose difference between maximum and minimum ASCII value of characters is exactly one
Given a string S consisting of lowercase English alphabets, the task is to find the length of the longest subsequence from the given string such that the difference between the largest and smallest ASCII value is exactly 1.
Examples:

Input: S = “acbbebcg”Output: 5Explanation: The longest subsequence of required type is “cbbbc”, whose length is 5.The difference between largest (‘c’) and smallest (‘b’) ASCII values is c – b = 99 – 98 = 1, which is minimum possible.
Input: S = “abcd”Output: 2Explanation: The longest subsequence of the required type is “ab”, whose length is 2. Other possible subsequences are “bc” and “cd”.The difference between largest(‘b’) and smallest(‘a’) ASCII values is b – a = 98 – 97 = 1.

Naive Approach: The simplest approach to solve the problem is to generate all possible subsequences of the given string S and print the length of the subsequence which is of maximum length and having a difference between ASCII values of the largest and smallest character is exactly equal to 1.Time Complexity: O(N * 2N)Auxiliary Space: O(N)
Efficient Approach: To optimize the above approach, the main idea is to use a Map to optimize the above approach. Follow the steps below to solve the problem:Initialize a variable, say maxLength, that stores the maximum length of the resultant subsequence.
Store the frequency of characters in a Map, say M.
Traverse the string and for each character, say ch, check if there exists character c with ASCII value (ch – 1) in the map M or not. If found to be true, then update maxLength as the maximum of maxLength and (M[ch] + M[ch – 1]).
After completing the above steps, print the value of maxLength as the result.
Below is the implementation of the above approach:

C++

#include
using namespace std;

int maximumLengthSubsequence(string str)
{

unordered_map 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