Two players share an array of non-negative whole numbers, nums. They take turns, and Player 1 goes first. On a turn, a player removes the first or the last remaining number and adds it to their own score. Both start at 0, and the game ends when the array is empty.
Both players always play their best. Return true if Player 1 ends with at least as many points as Player 2 (equal scores are good enough), and false otherwise.
Example 1
Input: nums = [2, 8, 3] Output: false Why: whichever end Player 1 takes, Player 2 takes 8; 5 loses to 8
2 more examples and the constraints
Example 2
Input: nums = [4, 2, 50, 6] Output: true Why: take 4; either end Player 2 takes leaves 50 open: 54 to 8
Example 3
Input: nums = [5, 5] Output: true Why: 5 each is a tie, and a tie goes to Player 1
Constraints
- 1 ≤ length of nums ≤ 20
- 0 ≤ nums[i] ≤ 10,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Try both ends, recursivelyO(2ⁿ)
- Interval DP tableO(n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 20 numbers | Verdict |
|---|---|---|---|
| Try both ends, recursively | O(2ⁿ) | Right idea, repeats every slice | |
| Interval DP table | O(n²) | Best; each slice solved once |
n = how many numbers are in the array.
Edge cases to test
- One number. [0] or [7]: Player 1 takes it and cannot lose.
- A tie. [5, 5]: equal scores still return true.
- All zeros. [0, 0, 0]: every game ends 0 to 0, so true.
- Odd length with a big middle. [1, 100, 1]: Player 2 always gets 100, so false.
Common mistakes
- Playing greedily, always taking the bigger end: in [4, 2, 50, 6], taking 6 first hands 50 to Player 2.
- Tracking both scores separately and forgetting that the opponent also plays their best.
- Returning lead > 0, which turns a tie into a loss.
How to talk through it
- 1Clarify. Does a tie count as a win? Are the numbers ever negative? Do both players play perfectly?
- 2Reduce to one number. Only the difference of the scores matters, so define the lead of the player to move on a slice.
- 3Give the recursion. Take an end, subtract the opponent’s best lead on the rest; say it is O(2ⁿ) with repeated slices.
- 4Fill the table. One cell per slice, from short to long; say which two cells each one reads.
- 5Test out loud. Run a single number, a tie, and [1, 100, 1] before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?