Easy to Medium
Chef wants to go to his home and there is a grid on the way. (The grid is a Square Matrix of size nn ).
And chef is Currently at the UpperLeftmost point (i.e. at 0,0) and his home is at the lower rightmost point (i.e. at n,n).
he is Restricted to move only either Right or Bottom.
Given the traveling Cost of each cell (means chef has to pay that amount to go from that cell) of the grid, the chef wants to reach his home and he has limited money,
your job is to tell the chef how much minimum money should chef take so that he will reach his home despite the choosen path
Find the maximum cost out of the possible two possible path for each move(step) taken by chef
sum(y, x) = max(sum(y, x−1),sum(y−1, x))+value[y][x] ,where x,y are indexes of grid
In this we will discuss Top Down (Tabulation ) Approach…
→ first make a dp Mtrix (2d array) for storing the answer of each value of n starting from 0 to n and initialize with 0th row and 0th column to 0;
→Now for each step find the maximum cost out of both the possible path . like this
dp[i][j] = max(dp[i][j-1],dp[i-1][j]) +input[i-1][j-1];
→ Now Print the Value at nth index of dp array
TIME COMPLEXITY :
For considering test case O(T*N^2)
T= no of test case and
using namespace std;
if(i==0 || j==0)sum[i][j]=0;
sum[i][j] = max(sum[i][j-1],sum[i-1][j]) +matrix[i-1][j-1];
Feel Free to share and discuss your approach here.