|
| 1 | +/** |
| 2 | + * Title: Stone Game VI |
| 3 | + * Description: The winner is the person with the most points after all the stones are chosen. If both players have the same amount of points, the game results in a draw. Both players will play optimally. Both players know the other's values. |
| 4 | + * Author: Hasibul Islam |
| 5 | + * Date: 06/05/2023 |
| 6 | + */ |
| 7 | + |
| 8 | +/** |
| 9 | + * @param {number[]} aliceValues |
| 10 | + * @param {number[]} bobValues |
| 11 | + * @return {number} |
| 12 | + */ |
| 13 | +var stoneGameVI = function (aliceValues, bobValues) { |
| 14 | + const length = bobValues.length; |
| 15 | + |
| 16 | + const turns = []; |
| 17 | + for (let i = 0; i < length; i++) { |
| 18 | + // in order to maximize profit for Bob and Alice calculate the sum of their values |
| 19 | + turns.push({ idx: i, sum: aliceValues[i] + bobValues[i] }); |
| 20 | + } |
| 21 | + |
| 22 | + // order the turns by the sum in descending order, so the most valuable turn will be the first |
| 23 | + turns.sort((a, b) => b.sum - a.sum); |
| 24 | + |
| 25 | + // let's start the game turn by turn. The result will store the difference between Alice and Bob scores |
| 26 | + let result = 0; |
| 27 | + for (let i = 0; i < length; i++) { |
| 28 | + const { idx } = turns[i]; |
| 29 | + if (i % 2 === 0) { |
| 30 | + // for all odd turns, we add to the result of Alice's value |
| 31 | + result += aliceValues[idx]; |
| 32 | + } else { |
| 33 | + // for all even turns, we subtract from the result of Bob's value |
| 34 | + result -= bobValues[idx]; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + // if the result is 0 return draw. Otherwise, return the winner |
| 39 | + if (!result) return result; |
| 40 | + return result > 0 ? 1 : -1; |
| 41 | +}; |
0 commit comments