3148. Maximum Difference Score in a Grid
Description
You are given an m x n
matrix grid
consisting of positive integers. You can move from a cell in the matrix to any other cell that is either to the bottom or to the right (not necessarily adjacent). The score of a move from a cell with the value c1
to a cell with the value c2
is c2 - c1
.
You can start at any cell, and you have to make at least one move.
Return the maximum total score you can achieve.
Example 1:
Input: grid = [[9,5,7,3],[8,9,6,1],[6,7,14,3],[2,5,3,1]]
Output: 9
Explanation: We start at the cell (0, 1)
, and we perform the following moves:
- Move from the cell (0, 1)
to (2, 1)
with a score of 7 - 5 = 2
.
- Move from the cell (2, 1)
to (2, 2)
with a score of 14 - 7 = 7
.
The total score is 2 + 7 = 9
.
Example 2:
Input: grid = [[4,3,2],[3,2,1]]
Output: -1
Explanation: We start at the cell (0, 0)
, and we perform one move: (0, 0)
to (0, 1)
. The score is 3 - 4 = -1
.
Constraints:
m == grid.length
n == grid[i].length
2 <= m, n <= 1000
4 <= m * n <= 105
1 <= grid[i][j] <= 105
Solutions
Solution 1: Dynamic Programming
According to the problem description, if the values of the cells we pass through are \(c_1, c_2, \cdots, c_k\), then our score is \(c_2 - c_1 + c_3 - c_2 + \cdots + c_k - c_{k-1} = c_k - c_1\). Therefore, the problem is transformed into: for each cell \((i, j)\) of the matrix, if we take it as the endpoint, what is the minimum value of the starting point.
We can use dynamic programming to solve this problem. We define \(f[i][j]\) as the minimum value of the path with \((i, j)\) as the endpoint. Then we can get the state transition equation:
So the answer is the maximum value of \(\textit{grid}[i][j] - \min(f[i-1][j], f[i][j-1])\).
The time complexity is \(O(m \times n)\), and the space complexity is \(O(m \times n)\). Where \(m\) and \(n\) are the number of rows and columns of the matrix, respectively.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|