Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]
.
The objective of the game is to end with the most stones. The total number of stones is odd, so there is no tie.
Alice and Bob take turns, with Alice starting first. Each player can take a pile of stones from either the beginning or the end of the row.
Return True
if Alice wins the game assuming both players play optimally, otherwise return False
.
To solve this problem optimally, we can use dynamic programming. But there’s a simpler realization: Since Alice always starts first and there is an even number of piles, Alice can always ensure she picks either all odd indexed piles or all even indexed piles.
0, 1, 2, 3, ..., n-1
, Alice can always select the parity (even-indexed or odd-indexed piles) that gives her the most stones.def stoneGame(piles):
return True
O(1)
, because the solution doesn’t require processing the array.O(1)
, as no additional space is required.Alice will always win given the conditions of the game and both players playing optimally. This simplification leverages the insight that starting first on an even-length pile array with an odd total sum ensures Alice can always secure the victory.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?