Input: ‘BLESSING1’ = “asdf” ‘BLESSING2’ = “asdf” ‘K’ = 3
Output: 317
The optimal strategy would be
To have the blessing as “sdf” which results in the total happiness of 115+100+102 = 317.
The first line consists of a number of test cases ‘T’.
The first line of each test case contains the string ‘BLESSING1’.
The second line of each test case contains the string ‘BLESSING2’.
The third line of each test case contains the length of common Subsequence 'K'.
The output consists of ‘T’ lines, each containing an integer that denotes the maximum happiness value the two blessings can generate.
You don't need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= length(BLESSING1), length(BLESSING2) <= 100
Time Limit: 1 sec
In this approach, we will recursively try out all possible common subsequences of length K. A recursive function is called for every combination of the ending index of the two strings and the length of the common subsequence. Let’s say a common subsequence is ending with the ‘i’ index in ‘BLESSING1’ and with the ‘j’ index in ‘BLESSING2’ and the length of the required common subsequence is ‘k’.
Our function returns the max value for a subsequence of length ‘k’ and ‘i’ and ‘j’ are a current index to ‘BLESSING1’ and ‘BLESSING2’. Thus we have 3 state variables. Now all you need to do is find the maximum value among all combinations of possible ‘i’, ‘j’, ’k’;
// Recursive function to find maximum happiness
The recursive approach discussed before can be optimized using memoization. We can memoize the result for each state with a particular ‘N’, ‘M’, and ‘K’, where ‘N’ and ‘M’ are the lengths of the strings. In this way, we can save time from recalculating the already calculated results.
For memoization let us define a matrix 3-dimensional array ‘DP’ of size ‘N’ x ‘M’ x ‘K’.
DP[i][j][k] - Maximum happiness that can be obtained in the subproblem BLESSING1 [ i…N-1], BLESSING2 [ j…M-1] with the length of subsequence as ‘K’.
// Recursive function to find the maximum score
// Recursive function to find maximum happiness
The idea is the same as memoization. At every step, we have two choices either skip the character of the first string or the second string. We have one more additional choice if the current character of both of the strings is the same, in this choice, we take the current character in the matching subsequence and move ahead.
In the end, we take the best of all the above choices.
DP[i][j][k] - Maximum happiness that can be obtained in the subproblem BLESSING1 [ i…N-1], BLESSING2 [ j…M-1] with the length of subsequence as ‘K’.