Minimum cost to make Longest Common Subsequence of length k | C ++ program to find subarray with sum closest to 0 ; Return Minimum cost to make LCS of length k ; If k is 0. ; If length become less than 0 , return big number . ; If state already calculated . ; Finding the cost ; Finding minimum cost and saving the state value ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 30 ; int solve ( char X [ ] , char Y [ ] , int l , int r , int k , int dp [ ] [ N ] [ N ] ) { if ( ! k ) return 0 ; if ( l < 0 r < 0 ) return 1e9 ; if ( dp [ l ] [ r ] [ k ] != -1 ) return dp [ l ] [ r ] [ k ] ; int cost = ( X [ l ] - ' a ' ) ^ ( Y [ r ] - ' a ' ) ; return dp [ l ] [ r ] [ k ] = min ( { cost + solve ( X , Y , l - 1 , r - 1 , k - 1 , dp ) , solve ( X , Y , l - 1 , r , k , dp ) , solve ( X , Y , l , r - 1 , k , dp ) } ) ; } int main ( ) { char X [ ] = " abble " ; char Y [ ] = " pie " ; int n = strlen ( X ) ; int m = strlen ( Y ) ; int k = 2 ; int dp [ N ] [ N ] [ N ] ; memset ( dp , -1 , sizeof dp ) ; int ans = solve ( X , Y , n - 1 , m - 1 , k , dp ) ; cout << ( ans == 1e9 ? -1 : ans ) << endl ; return 0 ; }