VOOZH about

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

⇱ Maximum sum path in a matrix from top to bottom - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum sum path in a matrix from top to bottom

Last Updated : 7 Dec, 2023

Consider a n*n matrix. Suppose each cell in the matrix has a value assigned. We can go from each cell in row i to a diagonally higher cell in row i+1 only [i.e from cell(i, j) to cell(i+1, j-1) and cell(i+1, j+1) only]. Find the path from the top row to the bottom row following the aforementioned condition such that the maximum sum is obtained.

Examples:

Input : mat[][] = { {5, 6, 1, 7},
{-2, 10, 8, -1},
{3, -7, -9, 11},
{12, -4, 2, 6} }
Output : 28
{5, 6, 1, 7},
{-2, 10, 8, -1},
{3, -7, -9, 11},
{12, -4, 2, 6} }
The highlighted numbers from top to bottom
gives the required maximum sum path.
(7 + 8 + 11 + 2) = 28

Method 1: The idea is to find maximum sum or all paths starting with every cell of first row and finally return maximum of all values in first row. We use Dynamic Programming as results of many subproblems are needed again and again.

Implementation:


Output
Maximum Sum = 28

Time Complexity: O(n2). 
Auxiliary Space: O(n2).

Method 2: Space-optimized approach:

To solve this problem with space complexity O(1), we can modify the input matrix itself to store the maximum sum that can be obtained up to each cell. In other words, we can use the same matrix to represent both the input matrix and the dynamic programming table.

We can start by initializing the first row of the matrix with the same values as the first row of the input matrix. Then, for each subsequent row i, we can update the values of the matrix using the values of the previous row, along with the value of the current cell in the input matrix.

The recurrence relation for the matrix can be expressed as:
mat[i][j] = max(mat[i-1][j-1], mat[i-1][j+1]) + mat[i][j]

After updating all the values in the matrix, the maximum sum can be obtained by finding the maximum value in the last row of the matrix. 

Step-by-step approach:

  • The first row of the matrix is left unchanged. 
  • For each subsequent row of the matrix, the maximum sum path is calculated. For this, another for loop is used to iterate through each element of the row.
  • The value of the current element in the matrix is updated by adding it to the maximum of its two adjacent elements in the previous row, i.e., the element to its top-right and top-left.
  • Then, find the maximum sum in the last row of the matrix

Below is the implementation of the above approach:


Output
28

Time Complexity: O(n^2). 
Auxiliary Space: O(1).

Comment
Article Tags: