|
| 1 | +/** |
| 2 | + * 1563. Stone Game V |
| 3 | + * https://leetcode.com/problems/stone-game-v/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * There are several stones arranged in a row, and each stone has an associated value which |
| 7 | + * is an integer given in the array stoneValue. |
| 8 | + * |
| 9 | + * In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and |
| 10 | + * right row), then Bob calculates the value of each row which is the sum of the values of all |
| 11 | + * the stones in this row. Bob throws away the row which has the maximum value, and Alice's |
| 12 | + * score increases by the value of the remaining row. If the value of the two rows are equal, |
| 13 | + * Bob lets Alice decide which row will be thrown away. The next round starts with the remaining |
| 14 | + * row. |
| 15 | + * |
| 16 | + * The game ends when there is only one stone remaining. Alice's is initially zero. |
| 17 | + * |
| 18 | + * Return the maximum score that Alice can obtain. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {number[]} stoneValue |
| 23 | + * @return {number} |
| 24 | + */ |
| 25 | +var stoneGameV = function(stoneValue) { |
| 26 | + const n = stoneValue.length; |
| 27 | + const prefixScore = Array.from({ length: n + 1 }, () => 0); |
| 28 | + const dp = Array.from({ length: n }, () => new Array(n).fill(-1)); |
| 29 | + |
| 30 | + for (let index = 1; index <= n; index++) { |
| 31 | + prefixScore[index] = prefixScore[index - 1] + stoneValue[index - 1]; |
| 32 | + } |
| 33 | + |
| 34 | + return getMaxScore(0, n - 1); |
| 35 | + |
| 36 | + function getMaxScore(left, right) { |
| 37 | + if (left >= right) return 0; |
| 38 | + if (dp[left][right] !== -1) return dp[left][right]; |
| 39 | + let result = 0; |
| 40 | + |
| 41 | + for (let index = left; index < right; index++) { |
| 42 | + const heap1 = prefixScore[index + 1] - prefixScore[left]; |
| 43 | + const heap2 = prefixScore[right + 1] - prefixScore[index + 1]; |
| 44 | + |
| 45 | + if (heap1 > heap2) { |
| 46 | + const score = heap2 + getMaxScore(index + 1, right); |
| 47 | + |
| 48 | + result = Math.max(score, result); |
| 49 | + } else if (heap1 < heap2) { |
| 50 | + const score = heap1 + getMaxScore(left, index); |
| 51 | + |
| 52 | + result = Math.max(score, result); |
| 53 | + } else { |
| 54 | + const score1 = heap2 + getMaxScore(index + 1, right); |
| 55 | + const score2 = heap1 + getMaxScore(left, index); |
| 56 | + |
| 57 | + result = Math.max(result, score1, score2); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + dp[left][right] = result; |
| 62 | + |
| 63 | + return result; |
| 64 | + } |
| 65 | +}; |
0 commit comments