|
| 1 | +/** |
| 2 | + * 1406. Stone Game III |
| 3 | + * https://leetcode.com/problems/stone-game-iii/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Alice and Bob continue their games with piles of stones. There are several stones arranged |
| 7 | + * in a row, and each stone has an associated value which is an integer given in the array |
| 8 | + * stoneValue. |
| 9 | + * |
| 10 | + * Alice and Bob take turns, with Alice starting first. On each player's turn, that player can |
| 11 | + * take 1, 2, or 3 stones from the first remaining stones in the row. |
| 12 | + * |
| 13 | + * The score of each player is the sum of the values of the stones taken. The score of each |
| 14 | + * player is 0 initially. |
| 15 | + * |
| 16 | + * The objective of the game is to end with the highest score, and the winner is the player |
| 17 | + * with the highest score and there could be a tie. The game continues until all the stones |
| 18 | + * have been taken. |
| 19 | + * |
| 20 | + * Assume Alice and Bob play optimally. |
| 21 | + * |
| 22 | + * Return "Alice" if Alice will win, "Bob" if Bob will win, or "Tie" if they will end the game |
| 23 | + * with the same score. |
| 24 | + */ |
| 25 | + |
| 26 | +/** |
| 27 | + * @param {number[]} stoneValue |
| 28 | + * @return {string} |
| 29 | + */ |
| 30 | +var stoneGameIII = function(stoneValue) { |
| 31 | + const n = stoneValue.length; |
| 32 | + const cache = new Array(n + 1).fill(null); |
| 33 | + |
| 34 | + function findOptimalScore(index) { |
| 35 | + if (index >= n) return 0; |
| 36 | + if (cache[index] !== null) return cache[index]; |
| 37 | + |
| 38 | + let maxScore = -Infinity; |
| 39 | + let currentSum = 0; |
| 40 | + |
| 41 | + for (let stones = 1; stones <= 3 && index + stones - 1 < n; stones++) { |
| 42 | + currentSum += stoneValue[index + stones - 1]; |
| 43 | + const opponentScore = findOptimalScore(index + stones); |
| 44 | + maxScore = Math.max(maxScore, currentSum + (index + stones < n ? -opponentScore : 0)); |
| 45 | + } |
| 46 | + |
| 47 | + cache[index] = maxScore; |
| 48 | + return maxScore; |
| 49 | + } |
| 50 | + |
| 51 | + const aliceScore = findOptimalScore(0); |
| 52 | + if (aliceScore > 0) return 'Alice'; |
| 53 | + if (aliceScore < 0) return 'Bob'; |
| 54 | + return 'Tie'; |
| 55 | +}; |
0 commit comments