Skip to content
Related Articles
Open in App
Not now

Related Articles

Find maximum path sum in a 2D matrix when exactly two left moves are allowed

Improve Article
Save Article
  • Difficulty Level : Expert
  • Last Updated : 31 Jan, 2023
Improve Article
Save Article

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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!