|
| 1 | +/** |
| 2 | + * Title: Stone Game III |
| 3 | + * Description: Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. |
| 4 | + * Author: Hasibul Islam |
| 5 | + * Date: 06/05/2023 |
| 6 | + */ |
| 7 | + |
| 8 | +/** |
| 9 | + * @param {number[]} stoneValue |
| 10 | + * @return {string} |
| 11 | + */ |
| 12 | +var stoneGameIII = function (stoneValue) { |
| 13 | + const dp = new Array(stoneValue.length).fill(-Infinity); |
| 14 | + for (let i = stoneValue.length - 1; i >= 0; i--) { |
| 15 | + let points = 0; |
| 16 | + for (let numStones = 1; numStones <= 3; numStones++) { |
| 17 | + if (i + numStones > stoneValue.length) break; |
| 18 | + points += stoneValue[i + numStones - 1]; |
| 19 | + dp[i] = Math.max(dp[i], points - (dp[i + numStones] || 0)); |
| 20 | + } |
| 21 | + } |
| 22 | + if (dp[0] === 0) return "Tie"; |
| 23 | + if (dp[0] > 0) return "Alice"; |
| 24 | + return "Bob"; |
| 25 | +}; |
0 commit comments