Alice and Bob play a game with piles of stones arranged in a row. Each pile holds a positive number of stones, piles[i].
They take turns, and Alice moves first. On each turn the current player takes the entire pile at either the beginning or the end of the row. The game ends when no piles are left, and each player's score is the total number of stones they took.
Alice wins only if she ends with strictly more stones than Bob; a tie is not a win for Alice. Assuming both players play optimally, return True if Alice wins and False otherwise.
Function Signature
def stone_game(piles: List[int]) -> bool:
Rules
-
Both players play optimally. Each one picks moves that maximize their own final total, which is the same as maximizing their lead, because every stone ends up with one of the two players.
-
The number of piles and the total number of stones can each be odd or even, so a tie is possible.
-
Return
True
only when Alice's total is strictly greater than Bob's.
Constraints
-
1 <= len(piles) <= 500
-
1 <= piles[i] <= 500
Examples
Input: piles = [5, 3, 4, 5]
Output: True
Alice takes a 5 from either end. Say she takes the left one, leaving [3, 4, 5]. If Bob takes the 5, Alice takes the 4 and Bob gets the 3, so Alice has 9 against Bob's 8. If Bob takes the 3, Alice takes the 5 and finishes with 10 against 7.
Input: piles = [1, 5, 2]
Output: False
Whichever end Alice takes, Bob can take the 5 next, and Alice gets the remaining small pile. She ends with 3 stones and Bob with 5.
Input: piles = [1, 2, 1]
Output: False
Alice must take a 1, Bob takes the 2, and Alice takes the last 1. Both players have 2 stones, and a tie is not a win for Alice.