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.
- First we calculate suffix sum in each row and store it in another 2D matrix call it bso 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])