Find maximum path sum in a 2D matrix when exactly two left moves are allowed
Given a 2D matrix arr[][] of dimensions N * M where N is number of rows and M is number of columns.The task is to find maximum path sum in this matrix satisfying some condition which are as follows :
- We can only start with arr[i][M] where 0 <= i <= N.
- We end the path on the same side, such that we can take exactly 2 left turns.
Example:

Examples:
Input : N = 3, M = 3 arr[][] = {{1, 2, 3}, {3, 3, 1}, {4, 1, 6}} Output : 20 Explanation :
If we follow this path then we get the sum 20.
Input : N = 3, M = 3
arr[][] = {{3, 7, 4},
{1, 9, 6},
{1, 7, 7}}
Output : 34
Explanation :
If we follow this path then we get the sum 34.
The idea is to use dynamic programming and select an optimal structure in the matrix i.e.
C shaped structure as shown in the below image.
Steps are as follows :
- First we calculate suffix sum in each row and store it in another 2D matrix call it b[][]so that at every valid index we get the sum of the entire row starting from that index.
b[i][j] = arr[i][j] + b[i][j + 1]
- Now we check each consecutive two rows and find the sum of their corresponding columns and simultaneously updating the maximum sum variable. Till now we have found both horizontal lines from that above structure.
sum = max(sum, b[i][j] + b[i – 1][j])
We need to find that vertical line connecting these horizontal lines i.e. column.
- After traversing each row, for each valid index we have two choices either we link this index to corresponding index of upper row i.e. add in previous column or start a new column.
Whichever value is maximum we retain that value and we update the value at this index.b[i][j] = max(b[i][j], b[i – 1][j] + arr[i][j])
Below is the implementation of the above approach:
C++
// C++ program to find maximum path sum// in a 2D matrix when exactly two// left moves are allowed#include <bits/stdc++.h>#define N 3#define M 3usingnamespacestd;// Function to return the maximum path sumintfindMaxSum(intarr[][M]){intsum = 0;intb[N][M];// Copy last column i.e. starting and// ending columns in another arrayfor(inti = 0; i < N; i++) {b[i][M - 1] = arr[i][M - 1];}// Calculate suffix sum in each rowfor(inti = 0; i < N; i++) {for(intj = M - 2; j >= 0; j--) {b[i][j] = arr[i][j] + b[i][j + 1];}}// Select the path we are going to followfor(inti = 1; i < N; i++) {for(intj = 0; j < M; j++) {sum = max(sum, b[i][j] + b[i - 1][j]);b[i][j] = max(b[i][j], b[i - 1][j] + arr[i][j]);}}returnsum;}// Driver Codeintmain(){intarr[N][M] = {{ 3, 7, 4 },{ 1, 9, 6 },{ 1, 7, 7 }};cout << findMaxSum(arr) << endl;return0;}Java
// Java program to find maximum path sum// in a 2D matrix when exactly two// left moves are allowedimportjava.io.*;classGFG{staticintN =3;staticintM =3;// Function to return the maximum path sumstaticintfindMaxSum(intarr[][]){intsum =0;int[][]b =newint[N][M];// Copy last column i.e. starting and// ending columns in another arrayfor(inti =0; i < N; i++){b[i][M -1] = arr[i][M -1];}// Calculate suffix sum in each rowfor(inti =0; i < N; i++){for(intj = M -2; j >=0; j--){b[i][j] = arr[i][j] + b[i][j +1];}}// Select the path we are going to followfor(inti =1; i < N; i++){for(intj =0; j < M; j++){sum = Math.max(sum, b[i][j] + b[i -1][j]);b[i][j] = Math.max(b[i][j], b[i -1][j] + arr[i][j]);}}returnsum;}// Driver Codepublicstaticvoidmain (String[] args){intarr[][] = {{3,7,4},{1,9,6},{1,7,7}};System.out.println (findMaxSum(arr));}}// This code is contributed by ajit.Python3
# Python3 program to find maximum path sum# in a 2D matrix when exactly two# left moves are allowedimportnumpy as npN=3M=3# Function to return the maximum path sumdeffindMaxSum(arr) :sum=0;b=np.zeros((N, M));# Copy last column i.e. starting and# ending columns in another arrayforiinrange(N) :b[i][M-1]=arr[i][M-1];# Calculate suffix sum in each rowforiinrange(N) :forjinrange(M-2,-1,-1) :b[i][j]=arr[i][j]+b[i][j+1];# Select the path we are going to followforiinrange(1, N) :forjinrange(M) :sum=max(sum, b[i][j]+b[i-1][j]);b[i][j]=max(b[i][j],b[i-1][j]+arr[i][j]);returnsum;# Driver Codeif__name__=="__main__":arr=[[3,7,4],[1,9,6],[1,7,7]];print(findMaxSum(arr));# This code is contributed by AnkitRai01C#
// C# program to find maximum path sum// in a 2D matrix when exactly two// left moves are allowedusingSystem;classGFG{staticintN = 3;staticintM = 3;// Function to return the maximum path sumstaticintfindMaxSum(int[,]arr){intsum = 0;int[,]b =newint[N, M];// Copy last column i.e. starting and// ending columns in another arrayfor(inti = 0; i < N; i++){b[i, M - 1] = arr[i, M - 1];}// Calculate suffix sum in each rowfor(inti = 0; i < N; i++){for(intj = M - 2; j >= 0; j--){b[i, j] = arr[i, j] + b[i, j + 1];}}// Select the path we are going to followfor(inti = 1; i < N; i++){for(intj = 0; j < M; j++){sum = Math.Max(sum, b[i, j] + b[i - 1, j]);b[i, j] = Math.Max(b[i, j], b[i - 1, j] + arr[i, j]);}}returnsum;}// Driver CodepublicstaticvoidMain (){int[,]arr = {{ 3, 7, 4 },{ 1, 9, 6 },{ 1, 7, 7 }};Console.WriteLine(findMaxSum(arr));}}/* This code contributed by PrinciRaj1992 */Output:34
Time Complexity :

- First we calculate suffix sum in each row and store it in another 2D matrix call it b[][]so that at every valid index we get the sum of the entire row starting from that index.


.png)
