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 across all the piles is odd, so there are no ties.

Alice and Bob take turns, with Alice starting first. Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins.

Assuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins.

Input & Output

Example 1 — Basic Game
$ Input: piles = [5,3,7,1]
Output: true
💡 Note: Alice takes 5 first, Bob takes 1, Alice takes 7, Bob takes 3. Alice gets 5+7=12, Bob gets 1+3=4. Alice wins with 12 > 4.
Example 2 — Different Strategy
$ Input: piles = [3,7,2,3]
Output: true
💡 Note: Alice takes 3 first, Bob takes 3, Alice takes 2, Bob takes 7. Alice gets 3+2=5, Bob gets 3+7=10. Wait - Alice should take 3 from right! Alice takes 3, Bob takes 3, Alice takes 7, Bob takes 2. Alice gets 3+7=10, Bob gets 3+2=5. Alice wins.
Example 3 — Mathematical Insight
$ Input: piles = [1,100,2,200]
Output: true
💡 Note: Even indices: 1+2=3, Odd indices: 100+200=300. Alice can force odd indices by taking from right first, guaranteeing she gets 300 > 3.

Constraints

  • 2 ≤ piles.length ≤ 500
  • piles.length is even
  • 1 ≤ piles[i] ≤ 500
  • sum(piles[i]) is odd

Visualization

Tap to expand
Stone Game - Optimal Solution INPUT Piles of Stones 5 idx 0 3 idx 1 7 idx 2 1 idx 3 piles = [5, 3, 7, 1] - Even number of piles - Take from START or END - Alice goes first - Total stones: 16 (odd) ALGORITHM STEPS 1 Observe Index Parity Even idx: 0,2 | Odd idx: 1,3 2 Calculate Sums Even sum: 5+7=12 Odd sum: 3+1=4 3 Alice's Strategy Alice can always pick all even OR all odd indices 4 Guaranteed Win Pick larger sum group 12 > 4, Alice wins! Even Idx Odd Idx piles[0]=5 piles[2]=7 Sum: 12 piles[1]=3 piles[3]=1 Sum: 4 FINAL RESULT ALICE WINS! Alice 12 Bob 4 12 > 4 Output: true Alice always wins with optimal play! Key Insight: Alice can always control whether she takes all even-indexed or all odd-indexed piles. Since total is odd, one group must have more stones. Alice picks that group and always wins. Time: O(1) | Space: O(1) - Just return true! Alice always wins with optimal play. TutorialsPoint - Stone Game | Optimal Solution
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
180.0K Views
Medium Frequency
~25 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen