Problem Description
You are given an m x n grid of positive integers. You may start at any cell and make at least one move. A move is allowed only to a cell that is either below (same column, higher row index) or to the right (same row, higher column index) of the current cell. The score of a move is the difference between the destination cell’s value and the source cell’s value. The total score of a series of moves is the sum of these differences (which telescopes to the difference between the final cell and the starting cell). The goal is to determine the maximum total score achievable by following these rules.
Key Insights
- Every valid sequence of moves has a final score equal to (final cell value – starting cell value) because the intermediate differences cancel out.
- The movement constraint (only move down or right) implies that the starting cell’s indices must be no greater than the final cell’s indices.
- To obtain the answer, we need to find the maximum difference grid[p][q] – grid[i][j] for any two cells such that i ≤ p and j ≤ q and the cells are not the same.
- A dynamic programming (or prefix computation) approach can be used to compute, for every cell, the minimum cell value from which it can be reached (in the allowed region), then update the answer using grid[i][j] minus that minimum.
- The trick is to be careful not to allow the starting cell to be the same as the destination; hence, when computing the “prefix minimum” for a cell, we exclude the cell itself.
Space and Time Complexity
Time Complexity: O(m * n) – We traverse the grid once to build the prefix minima and compute the difference for each cell. Space Complexity: O(m * n) – A separate 2D array is maintained to store the minimum values from valid predecessors.
Solution
We build a 2D helper array called bestBefore where bestBefore[i][j] is the minimum value among all cells in the submatrix defined by rows 0 to i and columns 0 to j excluding the current cell (i, j). This is computed iteratively: • For the first row (i = 0) with j > 0, the only predecessors are in the same row. • For the first column (j = 0) with i > 0, the only predecessors are in the same column. • For interior cells, the best candidate is the minimum from the cell just above, left, or the best values from previously computed portions. Then for every cell (except cell (0,0) where there is no predecessor) we calculate the potential score: grid[i][j] - bestBefore[i][j]. The final answer is the maximum of these scores.