-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1140. Stone Game II.java
37 lines (30 loc) · 1.07 KB
/
1140. Stone Game II.java
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
/* 1140. Stone Game II */
class Solution {
public int stoneGameII(int[] piles) {
int[] suffixSum = Arrays.copyOf(piles, piles.length);
for (int i = suffixSum.length - 2; i >= 0; i--){
suffixSum[i] += suffixSum[i + 1];
}
return maxStones(suffixSum, 1, 0, new int[piles.length][piles.length]);
}
private int maxStones(int[] suffixSum, int maxTillNow, int currIndex, int[][] memo){
if (currIndex + 2 * maxTillNow >= suffixSum.length){
return suffixSum[currIndex];
}
if (memo[currIndex][maxTillNow] > 0) return memo[currIndex][maxTillNow];
int res = Integer.MAX_VALUE;
for (int i = 1; i <= 2 * maxTillNow; i++) {
res = Math.min(
res,
maxStones(
suffixSum,
Math.max(i, maxTillNow),
currIndex + i,
memo
)
);
}
memo[currIndex][maxTillNow] = suffixSum[currIndex] - res;
return memo[currIndex][maxTillNow];
}
}