Longest Common Subsequence with at most k changes allowed | Python3 program to find LCS of two arrays with k changes allowed in the first array . ; Return LCS with at most k changes allowed . ; If at most changes is less than 0. ; If any of two array is over . ; Making a reference variable to dp [ n ] [ m ] [ k ] ; If value is already calculated , return that value . ; calculating LCS with no changes made . ; calculating LCS when array element are same . ; calculating LCS with changes made . ; Driven Program
MAX = 10 NEW_LINE def lcs ( dp , arr1 , n , arr2 , m , k ) : NEW_LINE INDENT if k < 0 : NEW_LINE INDENT return - ( 10 ** 7 ) NEW_LINE DEDENT if n < 0 or m < 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = dp [ n ] [ m ] [ k ] NEW_LINE if ans != - 1 : NEW_LINE INDENT return ans NEW_LINE DEDENT ans = max ( lcs ( dp , arr1 , n - 1 , arr2 , m , k ) , lcs ( dp , arr1 , n , arr2 , m - 1 , k ) ) NEW_LINE if arr1 [ n - 1 ] == arr2 [ m - 1 ] : NEW_LINE INDENT ans = max ( ans , 1 + lcs ( dp , arr1 , n - 1 , arr2 , m - 1 , k ) ) NEW_LINE DEDENT ans = max ( ans , lcs ( dp , arr1 , n - 1 , arr2 , m - 1 , k - 1 ) ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT k = 1 NEW_LINE arr1 = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE arr2 = [ 5 , 3 , 1 , 4 , 2 ] NEW_LINE n = len ( arr1 ) NEW_LINE m = len ( arr2 ) NEW_LINE dp = [ [ [ - 1 for i in range ( MAX ) ] for j in range ( MAX ) ] for k in range ( MAX ) ] NEW_LINE print ( lcs ( dp , arr1 , n , arr2 , m , k ) ) NEW_LINE DEDENT