Given two strings s1, s2 and K, find the length of the longest subsequence formed by consecutive segments of at least length K.
Input : s1 = aggayxysdfa s2 = aggajxaaasdfa k = 4 Output : 8 Explanation: aggasdfa is the longest subsequence that can be formed by taking consecutive segments, minimum of length 4. Here segments are "agga" and "sdfa" which are of length 4 which is included in making the longest subsequence. Input : s1 = aggasdfa s2 = aggajasdfaxy k = 5 Output : 5 Input: s1 = "aabcaaaa" s2 = "baaabcd" k = 3 Output: 4 Explanation: "aabc" is the longest subsequence that is formed by taking segment of minimum length 3. The segment is of length 4.
Prerequisite : Longest Common Subsequence
Create a LCS array where LCSi, j denotes the length of the longest common subsequence formed by characters of s1 till i and s2 till j having consecutive segments of at least length K. Create a cnt array to count the length of the common segment. cnti, j= cnti-1, j-1+1 when s1[i-1]==s2[j-1]. If characters are not equal then segments are not equal hence mark cnti, j as 0.
When cnti, j>=k, then update the lcs value by adding the value of cnti-a, j-a where a is the length of the segments a<=cnti, j. The answer for the longest subsequence with consecutive segments of at least length k will be stored in lcs[n][m] where n and m are the length of string1 and string2.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Maximum length of segments of 0's and 1's
- All possible strings of any length that can be formed from a given string
- K length words that can be formed from given characters without repetition
- Minimum length of the reduced Array formed using given operations
- Length of the longest substring with no consecutive same letters
- Longest palindrome formed by concatenating and reordering strings of equal length
- Find the number of binary strings of length N with at least 3 consecutive 1s
- Length of longest consecutive ones by at most one swap in a Binary String
- Maximize product of digit sum of consecutive pairs in a subsequence of length K
- Maximum length of consecutive 1's in a binary string in Python using Map function
- Find length of the longest consecutive path from a given starting character
- Strings formed from given characters without any consecutive repeating characters
- Count of Binary strings of length N having atmost M consecutive 1s or 0s alternatively exactly K times
- Maximum number of segments of lengths a, b and c
- Divide the array in K segments such that the sum of minimums is maximized
Improved By : Nikita tiwari