A sequence of characters placed in increasing order of their ASCII values is called an increasing sequence.
Input: S = “abcfgffs”
Explanation: Subsequence “abcfgs” is the longest increasing subsequence present in the string. Therefore, the length of the longest increasing subsequence is 6.
Input: S = “aaabac”
Approach: The idea is to use Dynamic Programming. Follow the steps given below to solve the problem:
- Initialize an array, say dp of size 26, to store at every ith index, the length of the longest increasing subsequence having (‘a’ + i)th character as the last character in the subsequence.
- Initialize variable, say lis, to store the length of the required subsequence.
- Iterate over each character of the string S.
- For every character encountered, i.e. S[i] – ‘a’, check for all characters, say j, with ASCII values smaller than that of the current character.
- Initialize a variable, say curr, to store the length of LIS ending with current character.
- Update curr with max(curr, dp[j]).
- Update length of the LIS, say lis, with max(lis, curr + 1).
- Update dp[S[i] – ‘a’] with max of d[S[i] – ‘a’] and curr.
- Finally, print the value of lis as the required length of LIS.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.