Given a N X N matrix Mat[N][N] of positive integers. There are only three possible moves from a cell (i, j)
- (i+1, j)
- (i+1, j-1)
- (i+1, j+1)
Starting from any column in row 0, return the largest sum of any of the paths up to row N-1.
Examples:
Input : mat[4][4] = { {4, 2, 3, 4},
{2, 9, 1, 10},
{15, 1, 3, 0},
{16, 92, 41, 44} };
Output :120
path : 4 + 9 + 15 + 92 = 120
Asked in: Amazon interview
The above problem can be recursively defined.
Let initial position be MaximumPathSum(N-1, j), where j varies from 0 to N-1. We return maximum value between all path that we start traversing (N-1, j) [ where j varies from 0 to N-1]
i = N-1, j = 0 to N -1
int MaximumPath(Mat[][N], I, j)
// IF we reached to first row of
// matrix then return value of that
// element
IF ( i == 0 && j = 0 )
return Mat[i][j]
// out of matrix bound
IF( i = N || j < 0 )
return 0;
// call all rest position that we reached
// from current position and find maximum
// between them and add current value in
// that path
return max(MaximumPath(Mat, i-1, j),
MaximumPath(Mat, i-1, j-1),
MaximumPath(Mat, i-1, j+1)))
+ Mat[i][j];
If we draw recursion tree of above recursive solution, we can observe overlapping subproblems. Since the problem has overlapping subproblems, we can solve it efficiently using Dynamic Programming. Below is Dynamic Programming based solution.
C++
// C++ program to find Maximum path sum // start any column in row '0' and ends // up to any column in row 'n-1' #include<bits/stdc++.h> using namespace std; #define N 4 // function find maximum sum path int MaximumPath(int Mat[][N]) { int result = 0 ; // creat 2D matrix to store the sum // of the path int dp[N][N+2]; // initialize all dp matrix as '0' memset(dp, 0, sizeof(dp)); // copy all element of first column into // 'dp' first column for (int i = 0 ; i < N ; i++) dp[0][i+1] = Mat[0][i]; for (int i = 1 ; i < N ; i++) for (int j = 1 ; j <= N ; j++) dp[i][j] = max(dp[i-1][j-1], max(dp[i-1][j], dp[i-1][j+1])) + Mat[i][j-1] ; // Find maximum path sum that end ups // at any column of last row 'N-1' for (int i=0; i<=N; i++) result = max(result, dp[N-1][i]); // return maximum sum path return result ; } // driver program to test above function int main() { int Mat[4][4] = { { 4, 2 , 3 , 4 }, { 2 , 9 , 1 , 10}, { 15, 1 , 3 , 0 }, { 16 ,92, 41, 44 } }; cout << MaximumPath ( Mat ) <<endl ; return 0; } |
Java
// Java program to find Maximum path sum // start any column in row '0' and ends // up to any column in row 'n-1' import java.util.*; class GFG { static int N = 4; // function find maximum sum path static int MaximumPath(int Mat[][]) { int result = 0; // creat 2D matrix to store the sum // of the path int dp[][] = new int[N][N + 2]; // initialize all dp matrix as '0' for (int[] rows : dp) Arrays.fill(rows, 0); // copy all element of first column into // 'dp' first column for (int i = 0; i < N; i++) dp[0][i + 1] = Mat[0][i]; for (int i = 1; i < N; i++) for (int j = 1; j <= N; j++) dp[i][j] = Math.max(dp[i - 1][j - 1], Math.max(dp[i - 1][j], dp[i - 1][j + 1])) + Mat[i][j - 1]; // Find maximum path sum that end ups // at any column of last row 'N-1' for (int i = 0; i <= N; i++) result = Math.max(result, dp[N - 1][i]); // return maximum sum path return result; } // driver code public static void main(String arg[]) { int Mat[][] = { { 4, 2, 3, 4 }, { 2, 9, 1, 10 }, { 15, 1, 3, 0 }, { 16, 92, 41, 44 } }; System.out.println(MaximumPath(Mat)); } } // This code is contributed by Anant Agarwal. |
Python3
# Python3 program to find # Maximum path sum # start any column in # row '0' and ends # up to any column in row 'n-1' N = 4 # function find maximum sum path def MaximumPath(Mat): result = 0 # create 2D matrix to store the sum # of the path # initialize all dp matrix as '0' dp = [[0 for i in range(N+2)] for j in range(N)] # copy all element of first column into # dp first column for i in range(N): for j in range(1, N+1): dp[i][j] = max(dp[i-1][j-1], max(dp[i-1][j], dp[i-1][j+1])) + \ Mat[i][j-1] # Find maximum path sum that end ups # at any column of last row 'N-1' for i in range(N+1): result = max(result, dp[N-1][i]) # return maximum sum path return result # driver program to test above function Mat = [[4, 2, 3, 4], [2, 9, 1, 10], [15, 1, 3, 0], [16, 92, 41, 44]] print(MaximumPath(Mat)) # This code is contributed by Soumen Ghosh. |
C#
// C# program to find Maximum path sum // start any column in row '0' and ends // up to any column in row 'n-1' using System; class GFG { static int N = 4; // function find maximum sum path static int MaximumPath(int [,] Mat) { int result = 0; // creat 2D matrix to store the sum // of the path int [,]dp = new int[N,N + 2]; // initialize all dp matrix as '0' //for (int[] rows : dp) // Arrays.fill(rows, 0); // copy all element of first column into // 'dp' first column for (int i = 0; i < N; i++) dp[0,i + 1] = Mat[0,i]; for (int i = 1; i < N; i++) for (int j = 1; j <= N; j++) dp[i,j] = Math.Max(dp[i - 1,j - 1], Math.Max(dp[i - 1,j], dp[i - 1,j + 1])) + Mat[i,j - 1]; // Find maximum path sum that end ups // at any column of last row 'N-1' for (int i = 0; i <= N; i++) result = Math.Max(result, dp[N - 1,i]); // return maximum sum path return result; } // driver code public static void Main() { int [,]Mat = { { 4, 2, 3, 4 }, { 2, 9, 1, 10 }, { 15, 1, 3, 0 }, { 16, 92, 41, 44 } }; Console.WriteLine(MaximumPath(Mat)); } } // This code is contributed by Ryuga. |
PHP
<?php // PHP program to find Maximum path sum // start any column in row '0' and ends // up to any column in row 'n-1' $N = 4; // function find maximum sum path function MaximumPath(&$Mat) { global $N; $result = 0; // creat 2D matrix to store the sum // of the path $dp = array_fill(0, $N, array_fill(0, $N + 2, NULL)); // copy all element of first column // into 'dp' first column for ($i = 0 ; $i < $N ; $i++) $dp[0][$i + 1] = $Mat[0][$i]; for ($i = 1 ; $i < $N ; $i++) for ($j = 1 ; $j <= $N ; $j++) $dp[$i][$j] = max($dp[$i - 1][$j - 1], max($dp[$i - 1][$j], $dp[$i - 1][$j + 1])) + $Mat[$i][$j - 1] ; // Find maximum path sum that end ups // at any column of last row 'N-1' for ($i = 0; $i <= $N; $i++) $result = max($result, $dp[$N - 1][$i]); // return maximum sum path return $result ; } // Driver Code $Mat = array(array(4, 2 , 3 , 4), array(2 , 9 , 1 , 10), array(15, 1 , 3 , 0), array(16 ,92, 41, 44)); echo MaximumPath ($Mat) . "\n" ; // This code is contributed by ita_c ?> |
Output:
120
Time complexity : O(N2)
This article is contributed by Nishant Singh . 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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.
Recommended Posts:
- Maximum weight path ending at any element of last row in a matrix
- Check if a path exists for a cell valued 1 to reach the bottom right corner of a Matrix before any cell valued 2
- Maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix
- Minimum moves taken to move coin of each cell to any one cell of Matrix
- Final direction after visiting every cell of Matrix starting from (0, 0)
- Number of shortest paths to reach every cell from bottom-left cell in the grid
- Maximum XOR of a path from top-left to bottom-right cell of given Matrix
- Find sum of all elements in a matrix except the elements in row and/or column of given cell?
- Represent a number as the sum of positive numbers ending with 9
- Maximize path sum from top-left cell to all other cells of a given Matrix
- Find length of the longest consecutive path from a given starting character
- Maximum sum of any submatrix of a Matrix which is sorted row-wise and column-wise
- Maximum cost path in an Undirected Graph such that no edge is visited twice in a row
- Check if row-major order path of Matrix is palindrome or not
- Print all possible paths from the first row to the last row in a 2D array
- Longest alternating (positive and negative) subarray starting at every index
- Maximum sum path in a matrix from top to bottom and back
- Paths from entry to exit in matrix and maximum path sum
- Sum of cost of all paths to reach a given cell in a Matrix
- Maximum sum of a Matrix where each value is from a unique row and column

