Maximum sum path in a matrix from top-left to bottom-right

Given a matrix mat[][] of dimensions N * M, the task is to find the path from the top-left cell (0, 0) to the bottom-right cell (N – 1, M – 1) of the given matrix such that sum of the elements in the path is maximum. The only moves allowed from any cell (i, j) of the matrix are (i + 1, j) or (i, j + 1).

Examples:

Input: mat[][] = {{3, 7}, {9, 8}}
Output: 20
Explanation:
Path with maximum sum is 3 => 9 => 8 as 20.

Input: mat[][] = {{1, 2}, {3, 5}}
Output: 9
Explanation:
Path with maximum sum is 1 => 3 => 5 as 9

Approach: The idea is to use Dynamic Programming to solve this problem. The key observation is that the cell mat[i][j] can only be reached from mat[i – 1][j] or mat[i][j – 1]. Therefore, the recurrence relation for this problem is given by the equation:



sum(i, j) = max(sum(i – 1, j), sum(i, j – 1)) + mat[i][j]

  1. Initialize an auxiliary matrix sum[][] of dimensions N * M.
  2. Iterate over the matrix elements and update each cell of the auxiliary matrix sum[][] using the above recurrence relation formed.
  3. After completing the above steps, the value sum[N][M] will contain the maximum sum possible for a path from the top-left corner to the bottom-right corner of the given matrix. Print that sum.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the maximum sum
// path in the grid
int MaximumPath(vector<vector<int> >& grid)
{
    // Dimensions of grid[][]
    int N = grid.size();
    int M = grid[0].size();
  
    // Stores maximum sum at each cell
    // sum[i][j] from cell sum[0][0]
    vector<vector<int> > sum;
    sum.resize(N + 1,
               vector<int>(M + 1));
  
    // Iterate to compute the maximum
    // sum path in the grid
    for (int i = 1; i <= N; i++) {
  
        for (int j = 1; j <= M; j++) {
  
            // Update the maximum path sum
            sum[i][j] = max(sum[i - 1][j],
                            sum[i][j - 1])
                        + grid[i - 1][j - 1];
        }
    }
  
    // Return the maximum sum
    return sum[N][M];
}
  
// Driver Code
int main()
{
    vector<vector<int> > grid
        = { { 1, 2 }, { 3, 5 } };
  
    cout << MaximumPath(grid);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for 
//the above approach
import java.util.*;
class GFG{
  
// Function to find the maximum sum
// path in the grid
static int MaximumPath(int [][]grid)
{
    // Dimensions of grid[][]
    int N = grid.length;
    int M = grid[0].length;
  
    // Stores maximum sum at each cell
    // sum[i][j] from cell sum[0][0]
    int [][]sum = new int[N + 1][M + 1];
  
    // Iterate to compute the maximum
    // sum path in the grid
    for (int i = 1; i <= N; i++) 
    {
        for (int j = 1; j <= M; j++) 
        {
            // Update the maximum path sum
            sum[i][j] = Math.max(sum[i - 1][j],
                                 sum[i][j - 1]) + 
                                 grid[i - 1][j - 1];
        }
    }
  
    // Return the maximum sum
    return sum[N][M];
}
  
// Driver Code
public static void main(String[] args)
{
  int [][]grid = {{1, 2}, {3, 5}};
  System.out.print(MaximumPath(grid));
}
}
  
// This code is contributed by shikhasingrajput

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
  
# Function to find the maximum sum
# path in the grid
def MaximumPath(grid):
  
    # Dimensions of grid[][]
    N = len(grid)
    M = len(grid[0])
  
    # Stores maximum sum at each cell
    # sum[i][j] from cell sum[0][0]
    sum = [[0 for i in range(M + 1)] 
              for i in range(N + 1)]
  
    # Iterate to compute the maximum
    # sum path in the grid
    for i in range(1, N + 1):
        for j in range(1, M + 1):
  
            # Update the maximum path sum
            sum[i][j] = (max(sum[i - 1][j],
                             sum[i][j - 1]) +
                        grid[i - 1][j - 1])
  
    # Return the maximum sum
    return sum[N][M]
  
# Driver Code
if __name__ == '__main__':
  
    grid = [ [ 1, 2 ], [ 3, 5 ] ] 
  
    print(MaximumPath(grid))
  
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
  
class GFG{
  
// Function to find the maximum sum
// path in the grid
static int MaximumPath(int [,]grid)
{
      
    // Dimensions of grid[,]
    int N = grid.GetLength(0);
    int M = grid.GetLength(1);
  
    // Stores maximum sum at each cell
    // sum[i,j] from cell sum[0,0]
    int [,]sum = new int[N + 1, M + 1];
  
    // Iterate to compute the maximum
    // sum path in the grid
    for(int i = 1; i <= N; i++) 
    {
        for(int j = 1; j <= M; j++) 
        {
            // Update the maximum path sum
            sum[i, j] = Math.Max(sum[i - 1, j],
                                 sum[i, j - 1]) + 
                                grid[i - 1, j - 1];
        }
    }
  
    // Return the maximum sum
    return sum[N, M];
}
  
// Driver Code
public static void Main(String[] args)
{
    int [,]grid = { { 1, 2 }, { 3, 5 } };
      
    Console.Write(MaximumPath(grid));
}
}
  
// This code is contributed by Amit Katiyar

chevron_right


Output: 

9

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.