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 - Space-Optimized DP INPUT Array: nums 1 idx 0 5 idx 1 2 idx 2 Game Rules: - Player 1 starts first - Take from either end - Both play optimally - P1 wins if score1 >= score2 Player 1 Score: 0 Player 2 Score: 0 nums = [1, 5, 2] ALGORITHM STEPS 1 Initialize 1D DP Array dp[i] = nums[i] (base case) 2 Iterate Subarrays Length 2 to n, start i to n-len 3 Update DP Value dp[i]=max(nums[i]-dp[i+1], nums[j]-dp[i]) 4 Return Result dp[0] >= 0 means P1 wins DP Array Simulation: Init: dp = [1, 5, 2] len=2: dp[1]=max(5-2,2-5)=3 len=2: dp[0]=max(1-5,5-1)=4 len=3: dp[0]=max(1-3,2-4)=-2 Final: dp[0] = -2 < 0 FINAL RESULT Optimal Play Simulation: Turn 1 (P1): Takes 2 Array: [1, 5] | P1: 2 Turn 2 (P2): Takes 5 Array: [1] | P2: 5 Turn 3 (P1): Takes 1 Array: [] | P1: 3, P2: 5 Final Scores: Player 1: 3 | Player 2: 5 3 < 5 -- P1 LOSES! Output: false Key Insight: dp[i] represents the score difference (current player - opponent) for subarray starting at index i. Space-optimized: Instead of 2D dp[i][j], we use 1D array updated in-place. Final dp[0] >= 0 means Player 1 wins. TutorialsPoint - Predict the Winner | Space-Optimized DP Approach
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