You are given an m x n
matrix grid
consisting of positive integers. You can move from a cell in the matrix to any other cell that is either to the bottom or to the right (not necessarily adjacent). The score of a move from a cell with the value c1
to a cell with the value c2
is c2 - c1
.
You can start at any cell, and you have to make at least one move.
Return the maximum total score you can achieve.
class Solution {
public:
int solve(vector<vector<int>>& grid,int n,int m,int i,int j,int mi,vector<vector<int>>& dp){
if(i>=n||j>=m) return INT_MIN;
int x = grid[i][j]-mi;
dp[i][j] = mi;
if(mi>grid[i][j]) mi = grid[i][j];
return max({x,solve(grid,n,m,i+1,j,mi,dp),solve(grid,n,m,i,j+1,mi,dp)});
}
int maxScore(vector<vector<int>>& grid) {
int n = grid.size();
int m = grid[0].size();
vector<vector<int>>dp(n,vector<int>(m,-1));
int mi = INT_MAX;
int ma = solve(grid,n,m,0,0,mi,dp);
return ma;
}
};
how to memoize it properly ,here the dp[i] stores the min element traverse till now.
Ashish Kumar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.