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
akkeshri140420012 hours ago
int maximumPath(int N, vector<vector<int>> Matrix)
   {
       // code here
       vector<vector<int>>dp(N,vector<int>(N));
       for(int i=N-1;i>=0;i--){
           for(int j=0;j<N;j++){
               if(i==N-1){
                   dp[i][j]=Matrix[i][j];
               }
               else if(j==0){
                   dp[i][j]=Matrix[i][j]+max(dp[i+1][j],dp[i+1][j+1]);
               }
               else if(j==N-1){
                   dp[i][j]=Matrix[i][j]+max(dp[i+1][j],dp[i+1][j-1]);
               }
               else{
                   dp[i][j]=Matrix[i][j]+max(dp[i+1][j],max(dp[i+1][j-1],dp[i+1][j+1]));
               }
           }
       }
       int maxi=INT_MIN;
       for(int i=0;i<N;i++){
           maxi=max(maxi,dp[0][i]);
       }
       return maxi;
   }
0
shivamcodes8 hours ago
C++ 0.28
int solve(int row, int col, vector<vector<int>> &Matrix, vector<vector<int>> &dp)
    {
        if(row<0 || col<0 || row>=Matrix.size() || col>=Matrix[0].size()) return 0;
        if(dp[row][col]!=-1) return dp[row][col];
        
        int a = solve(row+1, col, Matrix, dp);
        int b = solve(row+1, col-1, Matrix, dp);
        int c = solve(row+1, col+1, Matrix, dp);
        return dp[row][col]=Matrix[row][col]+max({a, b, c});
    }

    int maximumPath(int N, vector<vector<int>> Matrix)
    {
        // code here
        int row = 0;
        vector<vector<int>> dp(N, vector<int>(N,-1));
        int maxi = INT_MIN;
        for(int col = 0;col<Matrix[0].size();col++)
        {
            int ans = solve(row, col, Matrix, dp);
            maxi = max(maxi, ans);
        }
        return maxi;
    }
0
deveshgupta2314 days ago
O(N*N) Time Complexity
O(1) Space Complexity
int maximumPath(int N, vector<vector<int>> Matrix)
    {
        int res = 0;
        for(int i=0; i<N; i++){
            for(int j=0; j<N; j++){
                int val=0;
                if(i-1>=0) val = max(val, Matrix[i-1][j]);
                if(i-1>=0 && j-1>=0) val = max(val, Matrix[i-1][j-1]);
                if(i-1>=0 && j+1<N) val = max(val, Matrix[i-1][j+1]);
                
                Matrix[i][j] = Matrix[i][j] + val;
                res = max(Matrix[i][j], res);
            }
        }
        return res;
    }
0
rm8420731 week ago
int maximumPath(int N, vector<vector<int>> grid){
        int n = N;
        vector<vector<int>> dp(n, vector<int>(n, 0));
        
        for(int i=0;i<n;i++){
            dp[0][i] = grid[0][i];
        }
        
        for(int i=1;i<n;i++){
            for(int j=0;j<n;j++){
                int maxV = 0;
                if(i-1>=0) maxV = max(maxV, dp[i-1][j]);
                if(i-1>=0 && j+1<n)  maxV = max(maxV, dp[i-1][j+1]);
                if(i-1>=0 && j-1>=0)  maxV = max(maxV, dp[i-1][j-1]);
                
                dp[i][j] = maxV + grid[i][j];
            }
        }
        
        int ans = 0;
        
        for(int i=0;i<n;i++){
            ans = max(dp[n-1][i], ans);
        }
        
        return ans;
0
av8731 week ago
class Solution{
public:
    int dp[501][501];
    
    void initialise(){
        memset(dp, 0, sizeof dp);
    }
    int maximumPath(int N, vector<vector<int>> Matrix)
    {
        initialise();
        int maxVal=INT_MIN;
     
        
         for(int i=0; i<N; i++){
            for(int j=0; j<N; j++){
                
                
                if (i==0) //first row 
                    dp[i][j]=Matrix[i][j];
                    
                else if(j==0) //first col
                    dp[i][j]=max(dp[i-1][j], dp[i-1][j+1])+ Matrix[i][j];
                
                else if(j==N-1) //last col
                    dp[i][j]=max(dp[i-1][j], dp[i-1][j-1])+ Matrix[i][j];
                    
                else //rest
                dp[i][j]=
                    max(dp[i-1][j], 
                    max(dp[i-1][j-1],
                    dp[i-1][j+1])) + Matrix[i][j];
                
                maxVal=max(dp[i][j], maxVal);
        }
    }
             
        //  for(int i=0; i<N; i++){
        //     for(int j=0; j<N; j++){
        //         cout<<dp[i][j]<<" ";
        //     }
        //     cout<<endl;
        //   }
        
        return maxVal;
    }
};
+1
arorapankaj4712 weeks ago
Easy C++ Solution:-
Approach:
For any box we have three options of path whether it will come from upper part or upper left or upper right so compare every path and maximum of that part will be added with current matrix value and store in that box.
Code:-
int maximumPath(int n, vector<vector<int>> mat)   {       int dp[n+1][n+1]={};       for(int j=1;j<=n;j++)            dp[1][j]=mat[0][j-1];       for(int i=2;i<=n;i++){           for(int j=1;j<=n;j++){               dp[i][j]=mat[i-1][j-1]+max(max(dp[i-1][j],dp[i-1][j-1]),dp[i-1][j+1]);           }       }       int ans=0;       for(int j=1;j<=n;j++){           if(dp[n][j]>ans) ans=dp[n][j];       }       return ans;   }
+1
sayandas31082 weeks ago
Simple Java solution
Time Complexity: O(N^2)
Space Complexity: O(1)
Time: 0.86/2.61
class Solution{
    static int maximumPath(int n, int mat[][])
    {
        int ans=mat[0][0],i,j;
        for(i=1;i<n;i++)
            for(j=0;j<n;j++)
            {
                if(j==0)
                  mat[i][j]=mat[i][j]+Math.max(mat[i-1][j],mat[i-1][j+1]);
                else if(j==n-1)
                  mat[i][j]=mat[i][j]+Math.max(mat[i-1][j-1],mat[i-1][j]);
                else
                  mat[i][j]=mat[i][j]+Math.max(mat[i-1][j-1],Math.max(mat[i-1][j],mat[i-1][j+1]));
                
                ans=mat[i][j]>ans?mat[i][j]:ans;
            }
        
        return ans;
    }
}
+2
pradumana02 weeks ago
Simplest DP solution(Tabulation) C++ (Please Upvote)
int maximumPath(int n, vector<vector<int>> matrix)   {       // code here       int dp[n][n];       for(int i=0;i<n;i++)       dp[0][i]=matrix[0][i];       for(int i=1;i<n;i++)       {           for(int j=0;j<n;j++)           {               int a=INT_MIN,b=INT_MIN,c=INT_MIN;               if(i-1>=0&&j-1>=0)               a=dp[i-1][j-1];               b=dp[i-1][j];               if(i-1>=0&&j+1<n)               c=dp[i-1][j+1];               dp[i][j]=max(a,max(b,c))+matrix[i][j];           }       }       int maxy=INT_MIN;       for(int i=0;i<n;i++)       maxy=max(maxy,dp[n-1][i]);       return maxy;   }
+2
roboto7o32oo33 weeks ago
Clean C++ Solution ✨ ✨ (Using Memoization)
 
int solve(vector<vector<int>> &Matrix, int N, int i, int j, vector<vector<int>> &memo){
    if(i<0 or i>=N or j<0 or j>=N){
        return 0;
    }
    
    if(memo[i][j] != -1){
        return memo[i][j];
    }
    
    int down = solve(Matrix, N, i+1, j, memo);
    int right = solve(Matrix, N, i+1, j+1, memo);
    int left = solve(Matrix, N, i+1, j-1, memo);
    
    memo[i][j] = Matrix[i][j] + max({ down, right, left });
    return memo[i][j];
}

class Solution{
public:
    int maximumPath(int N, vector<vector<int>> Matrix)
    {
        vector<vector<int>> memo(N, vector<int>(N, -1));
        int result = 0;
        
        for(int i=0; i<N; i++){
            result = max(result, solve(Matrix, N, 0, i, memo));
        }
        
        return result;
    }
};
0
himanshukug19cs3 weeks ago
  for(int i=1;i<n;i++){           for(int j=0;j<n;j++){               if(j==0){                   m[i][j]=m[i][j]+Math.max(m[i-1][j],m[i-1][j+1]);               }               else if(j==n-1){                   m[i][j]=m[i][j]+Math.max(m[i-1][j],m[i-1][j-1]);               }               else                  m[i][j]=m[i][j]+Math.max(Math.max(m[i-1][j],m[i-1][j-1]),m[i-1][j+1]);           }       }       int ans=Integer.MIN_VALUE;       for(int i=0;i<n;i++){           ans=Math.max(m[n-1][i],ans);       }       return ans;
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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.