VOOZH about

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

⇱ Maximum path sum in matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum path sum in matrix

Last Updated : 29 Jan, 2025

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.

Approach:

The idea is to use dynamic programming to calculate the maximum path sum in a matrix. 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). This way, we propagate the maximum possible sum at each step. Finally, we find the maximum value in the last row and return it as the result.

Below is the implementation of the above approach:


Output
74

Time Complexity: O(n * m), where n is the number of rows and m is the number of columns, as we traverse the matrix once.
Auxiliary Space: O(1), since the matrix is updated in-place without using extra space.

Comment
Article Tags:
Article Tags: