|
| 1 | +/** |
| 2 | + * 1140. Stone Game II |
| 3 | + * https://leetcode.com/problems/stone-game-ii/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Alice and Bob continue their games with piles of stones. There are a number of piles arranged |
| 7 | + * in a row, and each pile has a positive integer number of stones piles[i]. The objective of |
| 8 | + * the game is to end with the most stones. |
| 9 | + * |
| 10 | + * Alice and Bob take turns, with Alice starting first. |
| 11 | + * |
| 12 | + * On each player's turn, that player can take all the stones in the first X remaining piles, |
| 13 | + * where 1 <= X <= 2M. Then, we set M = max(M, X). Initially, M = 1. |
| 14 | + * |
| 15 | + * The game continues until all the stones have been taken. |
| 16 | + * |
| 17 | + * Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {number[]} piles |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +var stoneGameII = function(piles) { |
| 25 | + const n = piles.length; |
| 26 | + const cache = new Map(); |
| 27 | + const suffixSums = new Array(n + 1).fill(0); |
| 28 | + |
| 29 | + for (let i = n - 1; i >= 0; i--) { |
| 30 | + suffixSums[i] = suffixSums[i + 1] + piles[i]; |
| 31 | + } |
| 32 | + |
| 33 | + return maxStones(0, 1); |
| 34 | + |
| 35 | + function maxStones(index, m) { |
| 36 | + if (index >= n) return 0; |
| 37 | + if (2 * m >= n - index) return suffixSums[index]; |
| 38 | + |
| 39 | + const key = `${index},${m}`; |
| 40 | + if (cache.has(key)) return cache.get(key); |
| 41 | + |
| 42 | + let opponentMin = Infinity; |
| 43 | + for (let x = 1; x <= 2 * m; x++) { |
| 44 | + opponentMin = Math.min(opponentMin, maxStones(index + x, Math.max(m, x))); |
| 45 | + } |
| 46 | + |
| 47 | + const result = suffixSums[index] - opponentMin; |
| 48 | + cache.set(key, result); |
| 49 | + return result; |
| 50 | + } |
| 51 | +}; |
0 commit comments