Determine whether the first player can finish with at least as many points as the second player when both players play optimally.
Predict the Winner
gfgProblem
You are given an array of integers nums. Two players take turns picking a number from either the start or the end of the array.
- Player 1 moves first.
- On each turn, a player must pick exactly one number from one of the two ends.
- The chosen number is added to that player's score and removed from the array.
- Both players play optimally to maximize their own final score.
Return true if Player 1 can end the game with a score greater than or equal to Player 2's score. Otherwise, return false.
Goal
Reason about the game under optimal play and decide whether the first player can avoid losing.
Input Format
- A single integer array
nums. - Each value represents the score gained when that number is picked.
Output Format
- Return a boolean value.
truemeans Player 1 can guarantee at least a tie.falsemeans Player 1 will end with a smaller score than Player 2.
Constraints
- The array contains at least 1 element.
- Values are integers.
- Players always pick from either end of the remaining array.
- Both players are assumed to play optimally.
Example 1
Input
nums = [1,5,2]
Output
false
Explanation
Player 1 can pick 1 or 2, but Player 2 will then take 5 and end up ahead.
Example 2
Input
nums = [1,5,233,7]
Output
true
Explanation
Player 1 can choose a sequence of moves that guarantees at least a tie, and in fact can win.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.