VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-sum-path-in-a-matrix/

⇱ Maximum sum path in a Matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum sum path in a Matrix

Last Updated : 12 Jul, 2025

Given an n*m matrix, the task is to find the maximum sum of elements of cells starting from the cell (0, 0) to cell (n-1, m-1). 
However, the allowed moves are right, downwards or diagonally right, i.e, from location (i, j) next move can be (i+1, j), or, (i, j+1), or (i+1, j+1). Find the maximum sum of elements satisfying the allowed moves.
Examples: 

Input:
mat[][] = {{100, -350, -200},
 {-100, -300, 700}}
Output: 500
Explanation: 
Path followed is 100 -> -300 -> 700

Input:
mat[][] = {{500, 100, 230},
 {1000, 300, 100},
 {200, 1000, 200}}
Explanation:
Path followed is 500 -> 1000 -> 300 -> 1000 -> 200

Naive Approach: Recursion

Going through the Naive approach by traversing every possible path. But, this is costly. So, use Dynamic Programming here in order to reduce the time complexity.


Output
3000

Time Complexity: O(2N*M

Auxiliary Space: O(N*M)

2. : Dynamic programming is used to solve the above problem in a recursive way.  

  1. Allot a position at the beginning of the matrix at (0, 0).
  2. Check each next allowed position from the current position and select the path with maximum sum.
  3. Take care of the boundaries of the matrix, i.e, if the position reaches the last row or last column then the only possible choice will be right or downwards respectively.
  4. Use a map to store track of all the visiting positions and before visiting any (i, j), check whether or not the position is visited before.
  5. Update the maximum of all possible paths returned by each recursive calls made.
  6. Go till the position reaches the destination cell, i.e, (n-1.m-1).

Below is the implementation of the above approach: 


Output
3000

Time Complexity: O(N*M)
Auxiliary Space: O(N*M) + O(N+M) -> O(NxM) is for the declared matrix of size nxm and O(N+M) is for the stack space (maximum recursive recursion calls).

3. : This approach will remove the extra space complexity i.e O(N+M) caused by recursion in the above approach. 

  1. Declare an array of size NxM - dp[N][M].
  2. Traverse through the created array row-wise and start filling the values in it.
  3. First row of the `dp` array i.e. index (0,j) ,where j represents column, will contain the values same as the first row of the given `matrix` array.
  4. Otherwise, we will calculate the values for up (i-1,j), right (i,j-1) and up_left_diagonal (i-1,j-1) for the current cell and the maximum value of them will be the value for the current cell ie dp[i][j].
  5. Finally, the maximum path sum of the matrix will be at dp[n-1][m-1] where n=no. of rows and m=no. of columns.

Output
500

Time complexity: O(NxM)

Auxiliary Space: O(NxM)

Comment
Article Tags:
Article Tags: