-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjava
More file actions
56 lines (43 loc) · 1.46 KB
/
Copy pathjava
File metadata and controls
56 lines (43 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.util.Arrays;
class Solution {
public int maxPathScore(int[][] grid, int k) {
int m = grid.length;
int n = grid[0].length;
final int NEG = -1_000_000_000;
int[][] prev = new int[n][k + 1];
for (int j = 0; j < n; j++) {
Arrays.fill(prev[j], NEG);
}
for (int i = 0; i < m; i++) {
int[][] curr = new int[n][k + 1];
for (int j = 0; j < n; j++) {
Arrays.fill(curr[j], NEG);
}
for (int j = 0; j < n; j++) {
int gain = grid[i][j];
int need = gain > 0 ? 1 : 0;
int limit = Math.min(k, i + j);
if (i == 0 && j == 0) {
curr[0][0] = 0;
continue;
}
for (int c = need; c <= limit; c++) {
int best = NEG;
if (i > 0 && prev[j][c - need] != NEG) {
best = Math.max(best, prev[j][c - need] + gain);
}
if (j > 0 && curr[j - 1][c - need] != NEG) {
best = Math.max(best, curr[j - 1][c - need] + gain);
}
curr[j][c] = best;
}
}
prev = curr;
}
int ans = NEG;
for (int c = 0; c <= k; c++) {
ans = Math.max(ans, prev[n - 1][c]);
}
return ans < 0 ? -1 : ans;
}
}