Stone Game VI Problem
Description
LeetCode Problem 1686.
Alice and Bob take turns playing a game, with Alice starting first.
There are n stones in a pile. On each player's turn, they can remove a stone from the pile and receive points based on the stone's value. Alice and Bob may value the stones differently.
You are given two integer arrays of length n, aliceValues and bobValues. Each aliceValues[i] and bobValues[i] represents how Alice and Bob, respectively, value the i^th stone.
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.
Determine the result of the game, and:
- If Alice wins, return
1. - If Bob wins, return
-1. - If the game results in a draw, return
0.
Example 1:
Input: aliceValues = [1,3], bobValues = [2,1]
Output: 1
Explanation:
If Alice takes stone 1 (0-indexed) first, Alice will receive 3 points.
Bob can only choose stone 0, and will only receive 2 points.
Alice wins.
Example 2:
Input: aliceValues = [1,2], bobValues = [3,1]
Output: 0
Explanation:
If Alice takes stone 0, and Bob takes stone 1, they will both have 1 point.
Draw.
Example 3:
Input: aliceValues = [2,4,3], bobValues = [1,6,7]
Output: -1
Explanation:
Regardless of how Alice plays, Bob will be able to have more points than Alice.
For example, if Alice takes stone 1, Bob can take stone 2, and Alice takes stone 0, Alice will have 6 points to Bob's 7.
Bob wins.
Constraints:
n == aliceValues.length == bobValues.length1 <= n <= 10^51 <= aliceValues[i], bobValues[i] <= 100
Solution
Approach: Greedy + Sorting
When a player takes stone i, they gain their own value of it and also stop the opponent from gaining theirs. So the stone is worth aliceValues[i] + bobValues[i] to whoever takes it, and both players should always take the remaining stone with the largest combined value.
Build vals[i] = (aliceValues[i] + bobValues[i], i) and sort it in descending order of the combined value. Alice takes the stones at even positions of vals and Bob the ones at odd positions. Add up each player's own values and compare them.
Complexity: O(n log n) time and O(n) space, where n is the number of stones.
class Solution:
def stoneGameVI(self, aliceValues: List[int], bobValues: List[int]) -> int:
vals = [(a + b, i) for i, (a, b) in enumerate(zip(aliceValues, bobValues))]
vals.sort(reverse=True)
a = sum(aliceValues[i] for _, i in vals[::2])
b = sum(bobValues[i] for _, i in vals[1::2])
if a > b:
return 1
if a < b:
return -1
return 0