Predict the Winner - Problem

You are given an integer array nums. Two players are playing a game with this array: player 1 and player 2.

Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0. At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or nums[nums.length - 1]) which reduces the size of the array by 1. The player adds the chosen number to their score.

The game ends when there are no more elements in the array. Return true if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true. You may assume that both players are playing optimally.

Input & Output

Example 1 — Player 1 Wins
$ Input: nums = [1,5,2]
Output: false
💡 Note: Player 1 takes 2, Player 2 takes 5, Player 1 takes 1. Player 1 gets 3, Player 2 gets 5. Player 2 wins.
Example 2 — Player 1 Wins Optimally
$ Input: nums = [1,5,233,7]
Output: true
💡 Note: Player 1 takes 1, Player 2 takes 7, Player 1 takes 233, Player 2 takes 5. Player 1 gets 234, Player 2 gets 12. Player 1 wins.
Example 3 — Equal Scores
$ Input: nums = [1,1]
Output: true
💡 Note: Player 1 takes any element and gets 1, Player 2 gets 1. Tie goes to Player 1.

Constraints

  • 1 ≤ nums.length ≤ 20
  • -107 ≤ nums[i] ≤ 107

Visualization

Tap to expand
Predict the Winner: [1,5,233,7]152337Players can only take from endsP1P1Take 1Take 7Optimal Strategy Analysis:If P1 takes 1: P2 takes 7, P1 gets 233, P2 gets 5If P1 takes 7: P2 takes 233, P1 gets 1+5=6, P2 gets 233Player 1 should take 1 first → Final score 234 vs 12Result: true (Player 1 wins)
Understanding the Visualization
1
Input
Array [1,5,233,7] with players taking turns
2
Optimal Play
Each player chooses to maximize their advantage
3
Winner
Player 1 wins if they can get ≥ 50% of total
Key Takeaway
🎯 Key Insight: Track score differences instead of absolute scores to determine optimal play
Asked in
Google 15 Microsoft 12 Amazon 8
78.0K Views
Medium Frequency
~25 min Avg. Time
2.8K 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