|
| 1 | +class Solution { |
| 2 | + public int stoneGameII(int[] piles) { |
| 3 | + Map<Integer, Integer> map = new HashMap<>(); |
| 4 | + int total = Arrays.stream(piles).sum(); |
| 5 | + return (total + dfs(0, 1, piles, map)) >> 1; |
| 6 | + } |
| 7 | + |
| 8 | + private int dfs(int s, int M, int[] piles, Map<Integer, Integer> map) { |
| 9 | + if (s >= piles.length) { |
| 10 | + return 0; |
| 11 | + } |
| 12 | + int key = s << 8 | M; |
| 13 | + if (map.containsKey(key)) { |
| 14 | + return map.get(key); |
| 15 | + } |
| 16 | + if (s + 2 * M >= piles.length) { |
| 17 | + int res = 0; |
| 18 | + for (int i = s; i < piles.length; ++i) { |
| 19 | + res += piles[i]; |
| 20 | + } |
| 21 | + return res; |
| 22 | + } |
| 23 | + int best = Integer.MIN_VALUE; |
| 24 | + int cur = 0; |
| 25 | + for (int x = 1; x <= 2 * M && s + x - 1 < piles.length; ++x) { |
| 26 | + cur += piles[s + x - 1]; |
| 27 | + best = Math.max(best, cur - dfs(s + x, Math.max(x, M), piles, map)); |
| 28 | + } |
| 29 | + map.put(key, best); |
| 30 | + return best; |
| 31 | + } |
| 32 | +} |
0 commit comments