|  | 
|  | 1 | +/** | 
|  | 2 | + * Title: Stone Game VII | 
|  | 3 | + * Description: Alice and Bob take turns playing a game, with Alice starting first. | 
|  | 4 | + * Author: Hasibul Islam | 
|  | 5 | + * Date: 06/05/2023 | 
|  | 6 | + */ | 
|  | 7 | + | 
|  | 8 | +/** | 
|  | 9 | + * @param {number[]} stones | 
|  | 10 | + * @return {number} | 
|  | 11 | + */ | 
|  | 12 | +var stoneGameVIII = function (stones) { | 
|  | 13 | + let prefix = Array(stones.length); | 
|  | 14 | + for (let i = 0; i < stones.length; i++) | 
|  | 15 | + prefix[i] = stones[i] + (prefix[i - 1] || 0); | 
|  | 16 | + | 
|  | 17 | + let dp = Array(stones.length).fill(0); | 
|  | 18 | + function game(idx) { | 
|  | 19 | + if (dp[idx]) return dp[idx]; | 
|  | 20 | + if (idx >= stones.length) return 0; | 
|  | 21 | + let skip = game(idx + 1); | 
|  | 22 | + let take = prefix[idx] - skip; | 
|  | 23 | + dp[idx] = take; | 
|  | 24 | + // Both Alice and Bob must maximize their scores, which would maximize the difference for Alice and minimize the difference for Bob | 
|  | 25 | + // Return the max score of either removing stones from the current idx or skipping to the next idx | 
|  | 26 | + return !skip ? take : Math.max(skip, take); | 
|  | 27 | + } | 
|  | 28 | + | 
|  | 29 | + return game(1); | 
|  | 30 | +}; | 
0 commit comments