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];
Implementation of naive recursion code:
 
C++
| #include <algorithm> // Required for std::max#include <iostream>#include <vector>intMaximumPath(std::vector<std::vector<int> >& Mat, inti,                intj){    intN = Mat.size();    // If we reached the first row of the matrix, return the    // value of that element    if(i == N - 1 && j == N - 1)        returnMat[i][j];    // Out of matrix bound    if(i >= N || i < 0        || j >= N || j < 0)        return0;    // Call all the rest positions that we reached from the    // current position and find the maximum between them    // and add the current value in that path    returnstd::max(               std::max(MaximumPath(Mat, i + 1, j),                        MaximumPath(Mat, i + 1, j - 1)),               MaximumPath(Mat, i + 1, j + 1))           + Mat[i][j];}intmain(){    // Example usage    std::vector<std::vector<int> > matrix        = { { 4, 2, 3, 4 },            { 2, 9, 1, 10 },            { 15, 1, 3, 0 },            { 16, 92, 41, 44 } };    intN = matrix.size();    intresult = MaximumPath(matrix, 0, 0);    std::cout << "Maximum Path Sum: "<< result              << std::endl;    return0;} | 
Java
| importjava.util.*;classMain {    publicstaticintmaximumPath(int[][] mat, inti, intj) {        intN = mat.length;        if(i == N - 1&& j == N - 1)            returnmat[i][j];        if(i >= N || i < 0|| j >= N || j < 0)            return0;        returnMath.max(                   Math.max(maximumPath(mat, i + 1, j), maximumPath(mat, i + 1, j - 1)),                   maximumPath(mat, i + 1, j + 1))               + mat[i][j];    }    publicstaticvoidmain(String[] args) {        int[][] matrix = {            {4, 2, 3, 4},            {2, 9, 1, 10},            {15, 1, 3, 0},            {16, 92, 41, 44}        };        intN = matrix.length;        intresult = maximumPath(matrix, 0, 0);        System.out.println("Maximum Path Sum: "+ result);    }} | 
Python3
| defmaximum_path(mat, i, j):    n =len(mat)    ifi ==n -1andj ==n -1:        returnmat[i][j]    ifi >=n ori < 0orj >=n orj < 0:        return0    returnmax(maximum_path(mat, i +1, j),               maximum_path(mat, i +1, j -1),               maximum_path(mat, i +1, j +1)) +mat[i][j]# Example usagematrix =[[4, 2, 3, 4],          [2, 9, 1, 10],          [15, 1, 3, 0],          [16, 92, 41, 44]]result =maximum_path(matrix, 0, 0)print("Maximum Path Sum:", result) | 
C#
| usingSystem;publicclassGFG{    publicstaticintMaximumPath(int[][] mat, inti, intj)    {        intN = mat.Length;        // If we reached the last row of the matrix, return the        // value of that element        if(i == N - 1 && j == N - 1)            returnmat[i][j];        // Out of matrix bound        if(i >= N || i < 0 || j >= N || j < 0)            return0;        // Call all the rest positions that we reached from the        // current position and find the maximum between them        // and add the current value in that path        returnMath.Max(            Math.Max(MaximumPath(mat, i + 1, j),                     MaximumPath(mat, i + 1, j - 1)),            MaximumPath(mat, i + 1, j + 1))            + mat[i][j];    }    publicstaticvoidMain()    {        // Example usage        int[][] matrix =        {            newint[] { 4, 2, 3, 4 },            newint[] { 2, 9, 1, 10 },            newint[] { 15, 1, 3, 0 },            newint[] { 16, 92, 41, 44 }        };        intN = matrix.Length;        intresult = MaximumPath(matrix, 0, 0);        Console.WriteLine("Maximum Path Sum: "+ result);    }} | 
Javascript
| functionMaximumPath(Mat, i, j) {    const N = Mat.length;    // If we reached the first row of the matrix, return the value of that element    if(i === N - 1 && j === N - 1)        returnMat[i][j];    // Out of matrix bound    if(i >= N || i < 0 || j >= N || j < 0)        return0;    // Call all the rest positions that we reached from the    // current position and find the maximum between them    // and add the current value in that path    returnMath.max(               Math.max(MaximumPath(Mat, i + 1, j),                        MaximumPath(Mat, i + 1, j - 1)),               MaximumPath(Mat, i + 1, j + 1))           + Mat[i][j];}functionmain() {    // Example usage    const matrix = [        [4, 2, 3, 4],        [2, 9, 1, 10],        [15, 1, 3, 0],        [16, 92, 41, 44]    ];    const N = matrix.length;    const result = MaximumPath(matrix, 0, 0);    console.log("Maximum Path Sum: "+ result);}main(); | 
Maximum Path Sum: 120
Time complexity : O(2N)
Auxiliary space: O(N)
Memoization DP:
In memoization DP, we introduced a dp table, which is a 2D vector of integers. The dp table is initialized with -1 to indicate that the results for each cell in the matrix haven’t been calculated yet.
During the recursive calls to the MaximumPath function, we check if the result for the current position (i, j) is already memoized in the dp table. If it is, we return the memoized result instead of recalculating it.
After calculating the maximum path sum for a position (i, j), we store the result in the corresponding cell of the dp table dp[i][j]. This way, we avoid redundant calculations for the same position and improve the efficiency of the algorithm.
Using memoization with a DP table helps reduce the time complexity of the algorithm by avoiding unnecessary recursive calls and reusing previously calculated results. It ensures that each subproblem is solved only once, leading to a more efficient solution for larger matrices.
 
C++
| #include <algorithm> // Required for std::max#include <iostream>#include <vector>intMaximumPath(std::vector<std::vector<int> >& Mat, inti,                intj, std::vector<std::vector<int> >& dp){    intN = Mat.size();    // If we reached the first row of the matrix, return the    // value of that element    if(i == N - 1 && j == N - 1)        returnMat[i][j];    // Out of matrix bound    if(i >= N || i < 0        || j >= N || j < 0)        return0;    if(dp[i][j] != -1)        returndp[i][j];    // Call all the rest positions that we reached from the    // current position and find the maximum between them    // and add the current value in that path    returndp[i][j]           = std::max(                 std::max(                     MaximumPath(Mat, i + 1, j, dp),                     MaximumPath(Mat, i + 1, j - 1, dp)),                 MaximumPath(Mat, i + 1, j + 1, dp))             + Mat[i][j];}intmain(){    // Example usage    std::vector<std::vector<int> > matrix        = { { 4, 2, 3, 4 },            { 2, 9, 1, 10 },            { 15, 1, 3, 0 },            { 16, 92, 41, 44 } };    intN = matrix.size();    std::vector<std::vector<int> > dp(        N, std::vector<int>(N, -1));    intresult = MaximumPath(matrix, 0, 0, dp);    std::cout << "Maximum Path Sum: "<< result              << std::endl;    return0;} | 
Java
| importjava.util.Arrays;importjava.util.List;publicclassMaximumPathSum {    publicstaticintmaximumPath(List<List<Integer>> matrix, inti, intj, int[][] dp) {        intn = matrix.size();        if(i == n - 1&& j == n - 1)            returnmatrix.get(i).get(j);        if(i >= n || i < 0|| j >= n || j < 0)            return0;        if(dp[i][j] != -1)            returndp[i][j];        intmaxPath = Math.max(Math.max(maximumPath(matrix, i + 1, j, dp),                maximumPath(matrix, i + 1, j - 1, dp)),                maximumPath(matrix, i + 1, j + 1, dp));        dp[i][j] = maxPath + matrix.get(i).get(j);        returndp[i][j];    }    publicstaticvoidmain(String[] args) {        List<List<Integer>> matrix = Arrays.asList(                Arrays.asList(4, 2, 3, 4),                Arrays.asList(2, 9, 1, 10),                Arrays.asList(15, 1, 3, 0),                Arrays.asList(16, 92, 41, 44)        );        intn = matrix.size();        int[][] dp = newint[n][n];        for(int[] row : dp) {            Arrays.fill(row, -1);        }        intresult = maximumPath(matrix, 0, 0, dp);        System.out.println("Maximum Path Sum: "+ result);    }} | 
Python3
| defmaximum_path(matrix, i, j, dp):    n =len(matrix)    ifi ==n -1andj ==n -1:        returnmatrix[i][j]    ifi >=n ori < 0orj >=n orj < 0:        return0    ifdp[i][j] !=-1:        returndp[i][j]    max_path =max(        max(maximum_path(matrix, i +1, j, dp),            maximum_path(matrix, i +1, j -1, dp)),        maximum_path(matrix, i +1, j +1, dp))    dp[i][j] =max_path +matrix[i][j]    returndp[i][j]# Example usagematrix =[[4, 2, 3, 4],          [2, 9, 1, 10],          [15, 1, 3, 0],          [16, 92, 41, 44]]n =len(matrix)dp =[[-1] *n for_ inrange(n)]result =maximum_path(matrix, 0, 0, dp)print("Maximum Path Sum:", result) | 
C#
| usingSystem;usingSystem.Collections.Generic;publicclassGFG{    publicstaticintMaximumPath(List<List<int>> matrix, inti, intj, int[,] dp)    {        intn = matrix.Count;    // If we reached the first row of the matrix, return the    // value of that element        if(i == n - 1 && j == n - 1)            returnmatrix[i][j];    // Out of matrix bound        if(i >= n || i < 0 || j >= n || j < 0)            return0;        if(dp[i, j] != -1)            returndp[i, j];    // Call all the rest positions that we reached from the    // current position and find the maximum between them    // and add the current value in that path        intmaxPath = Math.Max(Math.Max(MaximumPath(matrix, i + 1, j, dp),            MaximumPath(matrix, i + 1, j - 1, dp)),            MaximumPath(matrix, i + 1, j + 1, dp));        dp[i, j] = maxPath + matrix[i][j];        returndp[i, j];    }    publicstaticvoidMain(string[] args)    {   // Example usage        List<List<int>> matrix = newList<List<int>>()        {            newList<int>() { 4, 2, 3, 4 },            newList<int>() { 2, 9, 1, 10 },            newList<int>() { 15, 1, 3, 0 },            newList<int>() { 16, 92, 41, 44 }        };        intn = matrix.Count;        int[,] dp = newint[n, n];        for(inti = 0; i < n; i++)        {            for(intj = 0; j < n; j++)            {                dp[i, j] = -1;            }        }        intresult = MaximumPath(matrix, 0, 0, dp);        Console.WriteLine("Maximum Path Sum: "+ result);    }} | 
Javascript
| functionmaximum_path(matrix, i, j, dp) {    const n = matrix.length;    // Base case: If we reach the bottom-right corner, return the matrix value.    if(i === n - 1 && j === n - 1) {        returnmatrix[i][j];    }    // Base case: If we go out of bounds, return 0.    if(i >= n || i < 0 || j >= n || j < 0) {        return0;    }    // If the value has already been calculated, return it from dp array.    if(dp[i][j] !== -1) {        returndp[i][j];    }    // Calculate the maximum path by recursively exploring three directions.    const maxPath = Math.max(        maximum_path(matrix, i + 1, j, dp),        maximum_path(matrix, i + 1, j - 1, dp),        maximum_path(matrix, i + 1, j + 1, dp)    );    // Store the result in the dp array and return it.    dp[i][j] = maxPath + matrix[i][j];    returndp[i][j];}// Example usageconst matrix = [    [4, 2, 3, 4],    [2, 9, 1, 10],    [15, 1, 3, 0],    [16, 92, 41, 44]];const n = matrix.length;const dp = Array.from({ length: n }, () => Array(n).fill(-1));const result = maximum_path(matrix, 0, 0, dp);console.log("Maximum Path Sum:", result); | 
Maximum Path Sum: 120
Time complexity : O(N2)
Auxiliary space: O(N2)
Tabulation DP:
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. 
Implementation:
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>usingnamespacestd;#define N 4// function find maximum sum pathintMaximumPath(intMat[][N]){    intresult = 0 ;    // create 2D matrix to store the sum    // of the path    intdp[N][N+2];    // initialize all dp matrix as '0'    memset(dp, 0, sizeof(dp));    // copy all element of first row into    // 'dp' first row    for(inti = 0 ; i < N ; i++)        dp[0][i+1] = Mat[0][i];    for(inti = 1 ; i < N ; i++)        for(intj = 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(inti=0; i<=N; i++)        result = max(result, dp[N-1][i]);    // return maximum sum path    returnresult ;}// driver program to test above functionintmain(){    intMat[4][4] = { { 4, 2 , 3 , 4 },        { 2 , 9 , 1 , 10},        { 15, 1 , 3 , 0 },        { 16 ,92, 41, 44 }    };    cout << MaximumPath ( Mat ) <<endl ;    return0;} | 
Java
| // Java program to find Maximum path sum// start any column in row '0' and ends// up to any column in row 'n-1'importjava.util.*;publicclassGFG {        privatestaticintN = 4;    // function find maximum sum path    privatestaticintmaximumPath(intMat[][]){        intresult = 0;        // create 2D matrix to store the sum        // of the path        intdp[][] = newint[N][N + 2];        // copy all element of first row into        // 'dp' first row        for(inti = 0; i < N; i++)            dp[0][i + 1] = Mat[0][i];        for(inti = 1; i < N; i++)            for(intj = 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(inti = 0; i <= N; i++)            result = Math.max(result, dp[N - 1][i]);        // return maximum sum path        returnresult;    }        // driver code    publicstaticvoidmain(String arg[]){        intMat[][] = { { 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 pathdefMaximumPath(Mat):    result =0    # create 2D matrix to store the sum    # of the path    # initialize all dp matrix as '0'    dp =[[0fori inrange(N+2)] forj inrange(N)]    # copy all element of first row into    # dp first row    fori inrange(N):        forj inrange(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'    fori inrange(N+1):        result =max(result, dp[N-1][i])    # return maximum sum path    returnresult# driver program to test above functionMat =[[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' usingSystem;classGFG {         staticintN = 4;     // function find maximum sum path     staticintMaximumPath(int[,] Mat)     {         intresult = 0;         // create 2D matrix to store the sum         // of the path         int[,]dp = newint[N,N + 2];         // initialize all dp matrix as '0'         //for (int[] rows : dp)         //    Arrays.fill(rows, 0);         // copy all element of first row into         // 'dp' first row        for(inti = 0; i < N; i++)             dp[0,i + 1] = Mat[0,i];         for(inti = 1; i < N; i++)             for(intj = 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(inti = 0; i <= N; i++)             result = Math.Max(result, dp[N - 1,i]);         // return maximum sum path         returnresult;     }         // driver code     publicstaticvoidMain()     {         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.  | 
Javascript
| <script>// Javascript program to find Maximum path sum// start any column in row '0' and ends// up to any column in row 'n-1'        let N = 4;        // function find maximum sum path    functionMaximumPath(Mat)    {        let result = 0;          // create 2D matrix to store the sum        // of the path        let dp = newArray(N);                // initialize all dp matrix as '0'        for(let i=0;i<N;i++)        {            dp[i]=newArray(N+2);            for(let j=0;j<N+2;j++)            {                dp[i][j]=0;            }        }                  // copy all element of first row into        // 'dp' first row        for(let i = 0; i < N; i++)            dp[0][i + 1] = Mat[0][i];          for(let i = 1; i < N; i++)            for(let 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(let i = 0; i <= N; i++)            result = Math.max(result, dp[N - 1][i]);          // return maximum sum path        returnresult;    }        // driver code    let Mat = [[4, 2, 3, 4],       [2, 9, 1, 10],       [15, 1, 3, 0],       [16, 92, 41, 44]]    document.write(MaximumPath(Mat))         // This code is contributed by rag2127    </script> | 
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 pathfunctionMaximumPath(&$Mat){    global$N;    $result= 0;    // create 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 row    // into 'dp' first row    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));echoMaximumPath ($Mat) . "\n";// This code is contributed by ita_c?> | 
120
Time complexity : O(N2)
Auxiliary space: O(N2)
This article is contributed by Nishant Singh . If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


 
                                    







