Maximum path sum in matrix | Practice | GeeksforGeeks

Given a NxN matrix of positive integers. There are only three possible moves from a cell Matrix[r][c].

Matrix [r+1] [c]
Matrix [r+1] [c-1]
Matrix [r+1] [c+1]

Matrix [r+1] [c]
Matrix [r+1] [c-1]
Matrix [r+1] [c+1]
Starting from any column in row 0 return the largest sum of any of the paths up to row N-1.

Example 1:
Input: N = 2
Matrix = {{348, 391},
          {618, 193}}
Output: 1009
Explaination: The best path is 391 -> 618. 
It gives the sum = 1009.

Example 2:
Input: N = 2
Matrix = {{2, 2},
          {2, 2}}
Output: 4
Explaination: No matter which path is 
chosen, the output is 4.

Your Task:
You do not need to read input or print anything. Your task is to complete the function maximumPath() which takes the size N and the Matrix as input parameters and returns the highest maximum path sum.

Expected Time Complexity: O(N*N)
Expected Auxiliary Space: O(N*N)

Constraints:
1 ≤ N ≤ 500
1 ≤ Matrix[i][j] ≤ 1000
0
patildhiren444 days ago
JAVA - 0.88
Memoization
class Solution{
    
    static int memo(int i, int j, int[][]mat, int[][]dp){
        if(j<0 || j>mat[0].length-1){
            return 0;
        }
        
        if(i==mat.length-1){
            return mat[i][j];
        }
        
        if(dp[i][j]!=-1){
            return dp[i][j];
        }
        
        int a = mat[i][j]+ memo(i+1,j-1,mat,dp);
        int b = mat[i][j]+ memo(i+1,j,mat,dp);
        int c = mat[i][j]+ memo(i+1,j+1,mat,dp);
        
        dp[i][j] =Math.max(a, Math.max(b, c));;
        
        return Math.max(a, Math.max(b, c));
    }
    
    static int maximumPath(int n, int Matrix[][])
    {
        // code here
        int[][]dp = new int[n][n];
        
        for(int []row: dp){
            Arrays.fill(row, -1);
        }
        int maxi=0;
        for(int i=0; i<n; i++){
            maxi = Math.max(maxi,memo(0, i, Matrix, dp));
        }
        
        return maxi;
    }
}
0
vinaykush4 days ago
class Solution{
public:
    int findAns(int N,vector<vector<int>>& Matrix,int r,int c,vector<vector<int>>& dp){
        if(r>=N||c>=N||r<0||c<0)
        {
            return 0;
        }
        return Matrix[r][c]+max(max(dp[r+1][c]==0?dp[r+1][c]=findAns(N,Matrix,r+1,c,dp):dp[r+1][c],dp[r+1][c-1]==0?dp[r+1][c-1]=findAns(N,Matrix,r+1,c-1,dp):dp[r+1][c-1]),dp[r+1][c+1]==0?dp[r+1][c+1]=findAns(N,Matrix,r+1,c+1,dp):dp[r+1][c+1]);
    }
    int maximumPath(int N, vector<vector<int>> Matrix)
    {
        // code here
        int ans=0;
        vector<vector<int>> dp(N+1,vector<int>(N+1,0));
        for(int i=0;i<N;i++){
            ans=max(ans,findAns(N,Matrix,0,i,dp));
        }
        return ans;
        
    }
};
0
milindprajapatmst192 weeks ago
class Solution{
public:
    int maximumPath(int n, vector<vector<int>>& arr) {
        int result = arr[0][0];
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < n; j++) {
                int x = (j == 0) ? 0 : arr[i - 1][j - 1];
                int y = arr[i - 1][j];
                int z = (j == n - 1) ? 0 : arr[i - 1][j + 1];
                arr[i][j] += max({ x, y, z });
                if (i == n - 1)
                    result = max(result, arr[i][j]);
            }
        }
        return result;
    }
};
0
jainmuskan5652 weeks ago
int solve(int i,int j, vector<vector<int>>& mat, vector<vector<int>>&dp){       int r= mat.size(), col= mat[0].size();       if(j<0 || j>col-1){           return 0;       }       if(i==r-1){           return mat[i][j];       }       if(dp[i][j]!= -1){           return dp[i][j];       }       int a= mat[i][j]+ solve(i+1,j-1,mat,dp);       int b= mat[i][j]+ solve(i+1,j,mat,dp);       int c= mat[i][j]+ solve(i+1,j+1,mat,dp);       return dp[i][j]=max({a,b,c});   }   int maximumPath(int N, vector<vector<int>> Matrix)   {       vector<vector<int>> dp(N+1,vector<int>(N+1,-1));       int ans= 0;       for(int i=0;i<N;i++){           // check all the columns path then take max sum           ans=max(ans,solve(0,i,Matrix,dp));       }       return ans;   }
0
bokonist2 weeks ago
C++ 0.24s solution with comments, O(n*n) time and space
 
int maximumPath(int n, vector<vector<int>> m)
    {
        // code here
        int memo[n][n];
        for(int i=0;i<n;i++)
            fill(memo[i],memo[i]+n,0);
        for(int i=0;i<n;i++)
        {
            memo[n-1][i] = m[n-1][i]; // the bottom row will be the same as maxsum path bc it has nowhere to move below
        }
        int down, downLeft, downRight;
        for(int i=n-2;i>=0;i--) //populate the table from bottom up
        {
            for(int j=0;j<n;j++)
            {
                //check outofbounds and pick the max among the 3 options
                if(j-1 < 0)
                    downLeft=0;
                else
                    downLeft = memo[i+1][j-1];
                
                if(j+1 > n-1)
                    downRight=0;
                else
                    downRight= memo[i+1][j+1];
                
                down = memo[i+1][j];
                
                memo[i][j]= m[i][j] + max({down,downLeft,downRight});
            }
        }
        int mx = INT_MIN;
        for(int i=0;i<n;i++)
            mx=max(mx,memo[0][i]);
        return mx;
    }
+1
gulashanshashishekhar293 weeks ago
int n = Matrix.size(), maxSum = Matrix[0][0];
for (int i = 1; i < n; i++) {
    for (int j = 0; j < n; j++) {
        int m = Matrix[i-1][j];
        if (isValid(j-1, n)) m = max(m, Matrix[i-1][j-1]);
        if (isValid(j+1, n)) m = max(m, Matrix[i-1][j+1]);
        Matrix[i][j] += m;
        maxSum = max(maxSum, Matrix[i][j]);
    }
}
return maxSum;
0
2018eeb11381 month ago
int maximumPath(int n, vector<vector<int>> Matrix)
    {
        // code here
        int i,j;
        int dp[n+1][n+1];
        for(i= 0 ; i<=n;i++)
            for(j=0;j<=n;j++)
                dp[i][j] = 0;
        
        for(i= n-1 ; i>=0;i--)
        {
            for(j=n-1;j>=0;j--)
            {
                dp[i][j] = Matrix[i][j] + max({dp[i+1][j], dp[i+1][j-1], dp[i+1][j+1]});
            }
        }
        int sol = -1;
        for(i= 0 ; i<=n;i++)
        {
            sol = max(sol, dp[0][i]);
            /*for(j=0;j<=n;j++)
            {
                cout << dp[i][j] << " ";
            }*/
            //cout << endl;
        }
        
        return sol;
    }
0
khushiaggarwal09021 month ago
//Easiest Solution
//According to Aditya Verma approch
 
int maximumPath(int n, vector<vector<int>> mat)   {      int dp[n+1][n+1];       int ans=INT_MIN;       for(int i=0;i<=n;i++)       {                  for(int j=0;j<=n;j++)           {               if(i==0 || j==0)               {                    dp[i][j]=0;                }           }       }                     for(int i=1;i<n+1;i++)      for(int j=1;j<n+1;j++)       {                    int op1= mat[i-1][j-1]+ dp[i-1][j];         int  op2= mat[i-1][j-1]+dp[i-1][j-1];         int op3= mat[i-1][j-1] + dp[i-1][j+1];                            dp[i][j]=max({op1,op2,op3});                                }                 for(int i=1;i<n+1;i++)      for(int j=1;j<n+1;j++)      {          if(dp[i][j]>ans)          {              ans=dp[i][j];          }      }              return ans;   }
0
guptatushar110411 month ago
C++ solution using memoization approach having time complexity as O(N*N) and space complexity as O(N*N) is as follows :-
 
Execution Time :- 0.3 / 3.4 sec
 
int dp[1001][1001];   int solve(int i,int j,vector<vector<int>>& matrix)   {       if(j<0 or j>=matrix[0].size())       {           return 0;       }              if(i==0) return matrix[0][j];              if(dp[i][j]!=-1)           return dp[i][j];       int up=matrix[i][j]+solve(i-1,j,matrix);       int ld=matrix[i][j]+solve(i-1,j-1,matrix);       int rd=matrix[i][j]+solve(i-1,j+1,matrix);                    return dp[i][j]=max(up,max(ld,rd));
   }   int maximumPath(int N, vector<vector<int>>&matrix)   { memset(dp,-1,sizeof(dp));       // int m=matrix.size(),n=matrix[0].size();              int mini=INT_MIN;       for(int i=0;i<N;i++)       {          mini=max(mini,solve(N-1,i,matrix));       }              return mini;      }
0
hamidnourashraf1 month ago
recursive and too slow:
import math
class Solution:
    def rec_path(self, i, j, N, Matrix):
        if i < 0 or i > N-1:
            return -math.inf
        if j < 0 or j > N-1:
            return -math.inf
        if i == N-1:
            return Matrix[i][j]
        case1 = self.rec_path(i+1, j, N, Matrix)
        case2 = self.rec_path(i+1, j-1, N, Matrix)
        case3 = self.rec_path(i+1, j+1, N, Matrix)
        return Matrix[i][j] + max(case1, case2, case3)
        
    def maximumPath(self, N, Matrix):
        _max = -math.inf
        for j in range(N):
            _max = max(_max, self.rec_path(0, j, N, Matrix))
        return _max
recursive with memorization
import math
class Solution:
    def rec_path(self, i, j, N, Matrix, mem):
        if i < 0 or i > N-1:
            return -math.inf
        if j < 0 or j > N-1:
            return -math.inf
        if i == N-1:
            return Matrix[i][j]
        if mem[i][j] != -1:
            return mem[i][j]
        case1 = self.rec_path(i+1, j, N, Matrix, mem)
        case2 = self.rec_path(i+1, j-1, N, Matrix, mem)
        case3 = self.rec_path(i+1, j+1, N, Matrix, mem)
        mem[i][j] = Matrix[i][j] + max(case1, case2, case3)
        return mem[i][j]
    
    def maximumPath(self, N, Matrix):
        mem = [[-1]*(N) for j in range(N)]
        _max = -math.inf
        for j in range(N):
            _max = max(_max, self.rec_path(0, j, N, Matrix, mem))
        return _max
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.