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: Alice vs Bob5371Players take from either end alternatelyTake leftTake rightAlice's Strategy:Force access to better index groupEven: 5+7 = 12Odd: 3+1 = 4Alice always wins! 🏆
Understanding the Visualization
1
Input
Array of stone piles: [5,3,7,1]
2
Strategy
Alice can force even or odd indices
3
Victory
Alice wins with optimal play
Key Takeaway
🎯 Key Insight: Alice can always force a win by controlling which indexed piles she accesses through strategic end selection
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