|
| 1 | +/** |
| 2 | + * 1686. Stone Game VI |
| 3 | + * https://leetcode.com/problems/stone-game-vi/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Alice and Bob take turns playing a game, with Alice starting first. |
| 7 | + * |
| 8 | + * There are n stones in a pile. On each player's turn, they can remove a stone from the pile and |
| 9 | + * receive points based on the stone's value. Alice and Bob may value the stones differently. |
| 10 | + * |
| 11 | + * You are given two integer arrays of length n, aliceValues and bobValues. Each aliceValues[i] |
| 12 | + * and bobValues[i] represents how Alice and Bob, respectively, value the ith stone. |
| 13 | + * |
| 14 | + * The winner is the person with the most points after all the stones are chosen. If both players |
| 15 | + * have the same amount of points, the game results in a draw. Both players will play optimally. |
| 16 | + * Both players know the other's values. |
| 17 | + * |
| 18 | + * Determine the result of the game, and: |
| 19 | + * - If Alice wins, return 1. |
| 20 | + * - If Bob wins, return -1. |
| 21 | + * - If the game results in a draw, return 0. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {number[]} aliceValues |
| 26 | + * @param {number[]} bobValues |
| 27 | + * @return {number} |
| 28 | + */ |
| 29 | +var stoneGameVI = function(aliceValues, bobValues) { |
| 30 | + const n = aliceValues.length; |
| 31 | + const stones = aliceValues.map((alice, i) => ({ |
| 32 | + sum: alice + bobValues[i], |
| 33 | + alice: alice, |
| 34 | + bob: bobValues[i] |
| 35 | + })); |
| 36 | + |
| 37 | + stones.sort((a, b) => b.sum - a.sum); |
| 38 | + |
| 39 | + let aliceScore = 0; |
| 40 | + let bobScore = 0; |
| 41 | + |
| 42 | + for (let i = 0; i < n; i++) { |
| 43 | + if (i % 2 === 0) { |
| 44 | + aliceScore += stones[i].alice; |
| 45 | + } else { |
| 46 | + bobScore += stones[i].bob; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return aliceScore > bobScore ? 1 : aliceScore < bobScore ? -1 : 0; |
| 51 | +}; |
0 commit comments