Maximum path sum in matrix - GeeksforGeeks

Maximum path sum in matrix

Last Updated : 16 Oct, 2026

Given a matrix of size n * m. Find the maximum path sum in the matrix. The maximum path is the sum of all elements from the first row to the last row where you are allowed to move only down or diagonally to left or right. You can start from any element in the first row.

Examples: 

Input: mat[][] = 10 10 2 0 20 4
1 0 0 30 2 5
0 10 4 0 2 0
1 0 2 20 0 4
Output: 74
Explanation: The maximum sum path is 20-30-4-20.

Input: mat[][] = 1 2 3
9 8 7
4 5 6
Output: 17
Explanation: The maximum sum path is 3-8-6.

Try It Yourself
redirect icon

[Approach] Dynamic Programming Bottom-Up - O(n*m) Time and O(1) Space

The idea is to use dynamic programming to calculate the maximum path sum in a matrix.

  • We use the same matrix to store results intermediate steps.
  • Starting from the first row, for each cell in the matrix, we update its value by adding the maximum of the possible moves from the previous row (up, left, right).
  • Finally, we find the maximum value in the last row and return it as the result.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to find the maximum path sum
int maximumPath(vector<vector<int>>& mat) {
    int n = mat.size(), m = mat[0].size();
    
    // Initialize result with the maximum value in the first row
    int res = *max_element(mat[0].begin(), mat[0].end());
    
    // Traverse the matrix row by row
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < m; j++) {
            
            // Get max value from possible previous row positions
            int up = mat[i - 1][j];
            int left = (j > 0) ? mat[i - 1][j - 1] : 0;
            int right = (j < m - 1) ? mat[i - 1][j + 1] : 0;
            
            // Update current cell with max path sum
            mat[i][j] += max({up, left, right});
            
            // Update result if current cell has a greater value
            res = max(res, mat[i][j]);
        }
    }
    return res;
}

int main() {
  
    // Input matrix
    vector<vector<int>> mat = {{10, 10,  2,  0, 20,  4},
                                { 1,  0,  0, 30,  2,  5},
                                { 0, 10,  4,  0,  2,  0},
                                { 1,  0,  2, 20,  0,  4}};
    
    // Output the maximum path sum
    cout << maximumPath(mat) << endl;
    return 0;
}
Java
import java.util.*;

class GfG {
    
    // Function to find the maximum path sum
    public static int maximumPath(int[][] mat) {
        int n = mat.length, m = mat[0].length;
        
        // Initialize result with the maximum value in the first row
        int res = Arrays.stream(mat[0]).max().getAsInt();
        
        // Traverse the matrix row by row
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < m; j++) {
                
                // Get max value from possible previous row positions
                int up = mat[i - 1][j];
                int left = (j > 0) ? mat[i - 1][j - 1] : 0;
                int right = (j < m - 1) ? mat[i - 1][j + 1] : 0;
                
                // Update current cell with max path sum
                mat[i][j] += Math.max(up, Math.max(left, right));
                
                // Update result if current cell has a greater value
                res = Math.max(res, mat[i][j]);
            }
        }
        return res;
    }

    public static void main(String[] args) {
      
        // Input matrix
        int[][] mat = {
            {10, 10,  2,  0, 20,  4},
            { 1,  0,  0, 30,  2,  5},
            { 0, 10,  4,  0,  2,  0},
            { 1,  0,  2, 20,  0,  4}
        };
        
        // Output the maximum path sum
        System.out.println(maximumPath(mat));
    }
}
Python
def maximumPath(mat):
    n = len(mat)
    m = len(mat[0])

    res = max(mat[0])

    for i in range(1, n):
        for j in range(m):
            up = mat[i - 1][j]
            left = mat[i - 1][j - 1] if j > 0 else 0
            right = mat[i - 1][j + 1] if j < m - 1 else 0

            mat[i][j] += max(up, left, right)
            res = max(res, mat[i][j])

    return res


# Driver code
mat = [
    [10, 10, 2, 0, 20, 4],
    [1, 0, 0, 30, 2, 5],
    [0, 10, 4, 0, 2, 0],
    [1, 0, 2, 20, 0, 4]
]

print(maximumPath(mat))
C#
using System;
using System.Linq;

class GfG {
  
    // Function to find the maximum path sum
    static int MaximumPath(int[,] mat) {
        int n = mat.GetLength(0), m = mat.GetLength(1);
        
        // Initialize result with the maximum value in the first row
        int res = mat.Cast<int>().Take(m).Max();
        
        // Traverse the matrix row by row
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < m; j++) {
                
                // Get max value from possible previous row positions
                int up = mat[i - 1, j];
                int left = (j > 0) ? mat[i - 1, j - 1] : 0;
                int right = (j < m - 1) ? mat[i - 1, j + 1] : 0;
                
                // Update current cell with max path sum
                mat[i, j] += Math.Max(Math.Max(up, left), right);
                
                // Update result if current cell has a greater value
                res = Math.Max(res, mat[i, j]);
            }
        }
        return res;
    }

    static void Main() {
      
        // Input matrix
        int[,] mat = {
            {10, 10, 2, 0, 20, 4},
            {1, 0, 0, 30, 2, 5},
            {0, 10, 4, 0, 2, 0},
            {1, 0, 2, 20, 0, 4}
        };
        
        // Output the maximum path sum
        Console.WriteLine(MaximumPath(mat));
    }
}
JavaScript
function maximumPath(mat) {
    let n = mat.length, m = mat[0].length;
    
    // Initialize result with the maximum value in the first row
    let res = Math.max(...mat[0]);
    
    // Traverse the matrix row by row
    for (let i = 1; i < n; i++) {
        for (let j = 0; j < m; j++) {
            
            // Get max value from possible previous row positions
            let up = mat[i - 1][j];
            let left = (j > 0) ? mat[i - 1][j - 1] : 0;
            let right = (j < m - 1) ? mat[i - 1][j + 1] : 0;
            
            // Update current cell with max path sum
            mat[i][j] += Math.max(up, left, right);
            
            // Update result if current cell has a greater value
            res = Math.max(res, mat[i][j]);
        }
    }
    return res;
}

// Input matrix
let mat = [
    [10, 10, 2, 0, 20, 4],
    [1, 0, 0, 30, 2, 5],
    [0, 10, 4, 0, 2, 0],
    [1, 0, 2, 20, 0, 4]
];

// Output the maximum path sum
console.log(maximumPath(mat));

Output
74
Comment