Maximum sum path in a matrix from top to bottom and back

• Difficulty Level : Hard
• Last Updated : 15 Jul, 2021

Given a matrix of dimension N * M. The task is find the maximum sum of path from arr to arr[N – 1][M – 1] and back from arr[N – 1][M – 1] to arr
On the path from arr to arr[N – 1][M – 1], you can traverse in down and right directions and on the path from arr[N – 1][M – 1] to arr, you can traverse in up and left directions.
Note: Both the path must not be equal i.e. there has to be at least one cell arr[i][j] which is not common in both the paths.
Examples:

Input:
mat[][]= {{1, 0, 3, -1},
{3, 5, 1, -2},
{-2, 0, 1, 1},
{2, 1, -1, 1}}
Output: 16 Maximum sum on path from arr to arr
= 1 + 3 + 5 + 1 + 1 + 1 + 1 = 13
Maximum sum on path from arr to arr = 3
Total path sum = 13 + 3 = 16

Input:
mat[][]= {{1, 0},
{1, 1}}
Output: 3

Approach: This problem is somewhat similar to Minimum Cost Path problem except that in the present problem, two paths with maximum sum are to be found. Also, we need to take care that cells on both paths contribute only once to the sum.
First thing to notice is that path from arr[N – 1][M – 1] to arr is nothing but another path from arr to arr[N – 1][M – 1]. So, we have to find two paths from arr to arr[N – 1][M – 1] with maximum sum.
Approaching in a similar way as Minimum Cost Path problem, we start both paths from arr together and recur to neighbouring cells of the matrix till we reach arr[N – 1][M – 1]. To make sure that a cell doesn’t contribute more than once, we check if current cell on both path are the same or not. If they are same, it is added to the answer only once.
Below is the implementation of the above approach:

C++

 // C++ implementation of the approach#include using namespace std; // Input matrixint n = 4, m = 4;int arr = { { 1, 0, 3, -1 },                  { 3, 5, 1, -2 },                  { -2, 0, 1, 1 },                  { 2, 1, -1, 1 } }; // DP matrixint cache; // Function to return the sum of the cells// arr[i1][j1] and arr[i2][j2]int sum(int i1, int j1, int i2, int j2){    if (i1 == i2 && j1 == j2) {        return arr[i1][j1];    }    return arr[i1][j1] + arr[i2][j2];} // Recursive function to return the// required maximum cost pathint maxSumPath(int i1, int j1, int i2){     // Column number of second path    int j2 = i1 + j1 - i2;     // Base Case    if (i1 >= n || i2 >= n || j1 >= m || j2 >= m) {        return 0;    }     // If already calculated, return from DP matrix    if (cache[i1][j1][i2] != -1) {        return cache[i1][j1][i2];    }    int ans = INT_MIN;     // Recurring for neighbouring cells of both paths together    ans = max(ans, maxSumPath(i1 + 1, j1, i2 + 1) + sum(i1, j1, i2, j2));    ans = max(ans, maxSumPath(i1, j1 + 1, i2) + sum(i1, j1, i2, j2));    ans = max(ans, maxSumPath(i1, j1 + 1, i2 + 1) + sum(i1, j1, i2, j2));    ans = max(ans, maxSumPath(i1 + 1, j1, i2) + sum(i1, j1, i2, j2));     // Saving result to the DP matrix for current state    cache[i1][j1][i2] = ans;     return ans;} // Driver codeint main(){    memset(cache, -1, sizeof(cache));    cout << maxSumPath(0, 0, 0);     return 0;}

Java

 // Java implementation of the approachimport java.util.*; class GFG{     // Input matrixstatic int n = 4, m = 4;static int arr[][] = { { 1, 0, 3, -1 },                { 3, 5, 1, -2 },                { -2, 0, 1, 1 },                { 2, 1, -1, 1 } }; // DP matrixstatic int cache[][][] = new int; // Function to return the sum of the cells// arr[i1][j1] and arr[i2][j2]static int sum(int i1, int j1, int i2, int j2){    if (i1 == i2 && j1 == j2)    {        return arr[i1][j1];    }    return arr[i1][j1] + arr[i2][j2];} // Recursive function to return the// required maximum cost pathstatic int maxSumPath(int i1, int j1, int i2){     // Column number of second path    int j2 = i1 + j1 - i2;     // Base Case    if (i1 >= n || i2 >= n || j1 >= m || j2 >= m)    {        return 0;    }     // If already calculated, return from DP matrix    if (cache[i1][j1][i2] != -1)    {        return cache[i1][j1][i2];    }    int ans = Integer.MIN_VALUE;     // Recurring for neighbouring cells of both paths together    ans = Math.max(ans, maxSumPath(i1 + 1, j1, i2 + 1) + sum(i1, j1, i2, j2));    ans = Math.max(ans, maxSumPath(i1, j1 + 1, i2) + sum(i1, j1, i2, j2));    ans = Math.max(ans, maxSumPath(i1, j1 + 1, i2 + 1) + sum(i1, j1, i2, j2));    ans = Math.max(ans, maxSumPath(i1 + 1, j1, i2) + sum(i1, j1, i2, j2));     // Saving result to the DP matrix for current state    cache[i1][j1][i2] = ans;     return ans;} // Driver codepublic static void main(String args[]){    //set initial value    for(int i=0;i<5;i++)    for(int i1=0;i1<5;i1++)    for(int i2=0;i2<5;i2++)    cache[i][i1][i2]=-1;         System.out.println( maxSumPath(0, 0, 0));}} // This code is contributed by Arnab Kundu

Python3

 # Python 3 implementation of the approachimport sys # Input matrixn = 4m = 4arr = [[1, 0, 3, -1],    [3, 5, 1, -2],    [-2, 0, 1, 1],    [2, 1, -1, 1]] # DP matrixcache = [[[-1 for i in range(5)] for j in range(5)] for k in range(5)] # Function to return the sum of the cells# arr[i1][j1] and arr[i2][j2]def sum(i1, j1, i2, j2):    if (i1 == i2 and j1 == j2):        return arr[i1][j1]    return arr[i1][j1] + arr[i2][j2] # Recursive function to return the# required maximum cost pathdef maxSumPath(i1, j1, i2):         # Column number of second path    j2 = i1 + j1 - i2     # Base Case    if (i1 >= n or i2 >= n or j1 >= m or j2 >= m):        return 0     # If already calculated, return from DP matrix    if (cache[i1][j1][i2] != -1):        return cache[i1][j1][i2]    ans = -sys.maxsize-1     # Recurring for neighbouring cells of both paths together    ans = max(ans, maxSumPath(i1 + 1, j1, i2 + 1) + sum(i1, j1, i2, j2))    ans = max(ans, maxSumPath(i1, j1 + 1, i2) + sum(i1, j1, i2, j2))    ans = max(ans, maxSumPath(i1, j1 + 1, i2 + 1) + sum(i1, j1, i2, j2))    ans = max(ans, maxSumPath(i1 + 1, j1, i2) + sum(i1, j1, i2, j2))     # Saving result to the DP matrix for current state    cache[i1][j1][i2] = ans     return ans # Driver codeif __name__ == '__main__':    print(maxSumPath(0, 0, 0)) # This code is contributed by# Surendra_Gangwar

C#

 // C# implementation of the approachusing System; class GFG{     // Input matrixstatic int n = 4, m = 4;static int [,]arr = { { 1, 0, 3, -1 },                { 3, 5, 1, -2 },                { -2, 0, 1, 1 },                { 2, 1, -1, 1 } }; // DP matrixstatic int [,,]cache = new int[5, 5, 5]; // Function to return the sum of the cells// arr[i1][j1] and arr[i2][j2]static int sum(int i1, int j1, int i2, int j2){    if (i1 == i2 && j1 == j2)    {        return arr[i1, j1];    }    return arr[i1, j1] + arr[i2, j2];} // Recursive function to return the// required maximum cost pathstatic int maxSumPath(int i1, int j1, int i2){     // Column number of second path    int j2 = i1 + j1 - i2;     // Base Case    if (i1 >= n || i2 >= n || j1 >= m || j2 >= m)    {        return 0;    }     // If already calculated, return from DP matrix    if (cache[i1, j1, i2] != -1)    {        return cache[i1, j1, i2];    }    int ans = int.MinValue;     // Recurring for neighbouring cells of both paths together    ans = Math.Max(ans, maxSumPath(i1 + 1, j1, i2 + 1) + sum(i1, j1, i2, j2));    ans = Math.Max(ans, maxSumPath(i1, j1 + 1, i2) + sum(i1, j1, i2, j2));    ans = Math.Max(ans, maxSumPath(i1, j1 + 1, i2 + 1) + sum(i1, j1, i2, j2));    ans = Math.Max(ans, maxSumPath(i1 + 1, j1, i2) + sum(i1, j1, i2, j2));     // Saving result to the DP matrix for current state    cache[i1, j1, i2] = ans;     return ans;} // Driver codepublic static void Main(String []args){    //set initial value    for(int i = 0; i < 5; i++)        for(int i1 = 0; i1 < 5; i1++)            for(int i2 = 0; i2 < 5; i2++)                cache[i,i1,i2]=-1;         Console.WriteLine( maxSumPath(0, 0, 0));}} // This code contributed by Rajput-Ji

Javascript


Output:
16

Time Complexity: O((N2) * M)

My Personal Notes arrow_drop_up