解释说明:
上面的内容的意思是为了有只移动一次的情况,而后面的grid(i,j)-grid(i,k)由于j严格大于k,所以至少移动了一次,前面可以保持不移动,不移动就是选择0。
class Solution {
public int maxScore(List<List<Integer>> grid) {
int m = grid.size(), n = grid.get(0).size();
int[][] prerow = new int[m][n];
int[][] precol = new int[m][n];
int[][] f = new int[m][n];
for (int i = 0; i < m; ++i) {
Arrays.fill(f[i], Integer.MIN_VALUE);
}
int ans = Integer.MIN_VALUE;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (i > 0) {
f[i][j] = Math.max(f[i][j], grid.get(i).get(j) + precol[i - 1][j]);
}
if (j > 0) {
f[i][j] = Math.max(f[i][j], grid.get(i).get(j) + prerow[i][j - 1]);
}
ans = Math.max(ans, f[i][j]);
prerow[i][j] = precol[i][j] = Math.max(f[i][j], 0) - grid.get(i).get(j);
if (i > 0) {
precol[i][j] = Math.max(precol[i][j], precol[i - 1][j]);
}
if (j > 0) {
prerow[i][j] = Math.max(prerow[i][j], prerow[i][j - 1]);
}
}
}
return ans;
}
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/maximum-difference-score-in-a-grid/solutions/2877233/ju-zhen-zhong-de-zui-da-de-fen-by-leetco-c5tv/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。