![]() |
VOOZH | about |
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:
Maximum Sum = 28
Time Complexity: O(n2).
Auxiliary Space: O(n2).
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:
Below is the implementation of the above approach:
28
Time Complexity: O(n^2).
Auxiliary Space: O(1).