|
| 1 | +/** |
| 2 | + * 1690. Stone Game VII |
| 3 | + * https://leetcode.com/problems/stone-game-vii/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Alice and Bob take turns playing a game, with Alice starting first. |
| 7 | + * |
| 8 | + * There are n stones arranged in a row. On each player's turn, they can remove either the leftmost |
| 9 | + * stone or the rightmost stone from the row and receive points equal to the sum of the remaining |
| 10 | + * stones' values in the row. The winner is the one with the higher score when there are no stones |
| 11 | + * left to remove. |
| 12 | + * |
| 13 | + * Bob found that he will always lose this game (poor Bob, he always loses), so he decided to |
| 14 | + * minimize the score's difference. Alice's goal is to maximize the difference in the score. |
| 15 | + * |
| 16 | + * Given an array of integers stones where stones[i] represents the value of the ith stone from |
| 17 | + * the left, return the difference in Alice and Bob's score if they both play optimally. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {number[]} stones |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +var stoneGameVII = function(stones) { |
| 25 | + const n = stones.length; |
| 26 | + const prefixSum = new Array(n + 1).fill(0); |
| 27 | + const dp = new Array(n).fill().map(() => new Array(n).fill(0)); |
| 28 | + |
| 29 | + for (let i = 0; i < n; i++) { |
| 30 | + prefixSum[i + 1] = prefixSum[i] + stones[i]; |
| 31 | + } |
| 32 | + |
| 33 | + for (let len = 2; len <= n; len++) { |
| 34 | + for (let start = 0; start <= n - len; start++) { |
| 35 | + const end = start + len - 1; |
| 36 | + const leftScore = prefixSum[end + 1] - prefixSum[start + 1] - dp[start + 1][end]; |
| 37 | + const rightScore = prefixSum[end] - prefixSum[start] - dp[start][end - 1]; |
| 38 | + dp[start][end] = Math.max(leftScore, rightScore); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + return dp[0][n - 1]; |
| 43 | +}; |
0 commit comments