I am not able to understand why we need to keep a separate state for k .
For arrays A and B , indices i and j.
I applied the logic that :
- If elements of A and B are same ,
dp[i][j] = 1 + dp[i-1][j-1]
and proceed to i+1 and j+1 as normal . - If both are different , find if we really need to edit the
A[i]
using k , i.e if after editing it we are getting1+dp[i-1][j-1]
as greater thandp[i-1][j]
anddp[i][j-1].
I am able to pass several test cases but not all .
Please see through code
int lenModifiedLCS(vector<int>& A,vector<int>&B,int k)
{
int N = A.size();
int M = B.size();
vector<vector<int>> dp(N+1,vector<int>(M+1,0));
for(int i=1;i<=N;i++)
{
for(int j=1;j<=M;j++)
{
// i-1 and j-1 are indices of arrays
// i and j are indices of dp table
if(A[i-1] == B[j-1])
{
dp[i][j] = 1 + dp[i-1][j-1];
}
else
{
int possibleChange = 1 + dp[i-1][j-1];
if(
k>0 &&
(possibleChange == max(max(possibleChange,dp[i-1][j]) , dp[i][j-1])) &&
(possibleChange != dp[i-1][j]) && (possibleChange!=dp[i][j-1])
)
{
A[i-1] = B[j-1];
dp[i][j] = possibleChange;
k--;
}
else
{
dp[i][j] = max( dp[i-1][j] , dp[i][j-1] );
}
}
}
}
// for(int i=0;i<N+1;i++)
// {
// for(int j = 0;j<M+1;j++)
// {
// cout<<setw(3)<<dp[i][j]<<" ";
// }
// cout<<"\n";
// }
return dp[N][M];
}