Tuesday, June 9, 2026
HomeData Modelling & AIFind maximum path sum in a 2D matrix when exactly two left...

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 :

  1. We can only start with arr[i][M] where 0 <= i <= N.
  2. We end the path on the same side, such that we can take exactly 2 left turns.
    1. 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]

  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])

  1. We need to find that vertical line connecting these horizontal lines i.e. column.
  2. 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])

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

3 COMMENTS

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6895 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7018 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS