Given an M × N matrix of non-negative integers where each cell contains a coin of some denomination, collect the maximum value of coins by traversing the grid.

The first traversal starts from the top-left corner of the matrix and ends in the bottom-left corner, and the second traversal starts from the top-right corner and ends in the bottom-right corner. From any cell (i, j) in the matrix, we are allowed to move to cell (i+1, j+1) or (i+1, j-1) or (i+1, j). If both traversals pass through the same cell, only one can collect coins from that cell.

 
For example,

Input:  The given matrix is
 
[ 0 2 4 1 ]
[ 4 8 3 7 ]
[ 2 3 6 2 ]
[ 9 7 8 3 ]
[ 1 5 9 4 ]
 
Output: The maximum coins collected is 47 (Red coins + Blue coins)

Practice this problem

The idea is to simultaneously start both traversals from the top-left corner (0, 0) and the top-right corner (0, N-1) of the matrix. For each step, the row number would increase by one and the column number might remain the same or can increase/decrease by 1, i.e., (i, j) —> (i+1, j-1) or (i+1, j) or (i+1, j+1).

We collect the coins as we move along and return the maximum possible collection. The recursive algorithm can be implemented as follows in C, Java, and Python:

C++


Download  Run Code

Output:

The maximum coins collected is 47

Java


Download  Run Code

Output:

The maximum coins collected is 47

Python


Download  Run Code

Output:

The maximum coins collected is 47

The time complexity of the proposed solution is exponential since it recomputes the same subproblems repeatedly. We can easily optimize the code to run in O(M × N2) time using dynamic programming. The idea is to store the results of function calls and use the cached result when the same input occurs again. The dynamic programming solution is left as an exercise to the readers.