MediumArrayMathDynamic ProgrammingRecursionGame Theory

Predict the Winner

LeetCode
1 approach, code in all languages

You are given an integer array nums. Two players take turns, and Player 1 moves first. On each turn a player takes either the first or the last element of the remaining array and adds its value to their own running score; the chosen element is then removed.

When no elements remain, the game ends. Assuming both players play optimally to maximize their own score, return true if Player 1 can finish with a score greater than or equal to Player 2, and false otherwise. If the scores are tied, Player 1 is considered the winner.

Example 1

Input: nums = [1,5,2]

Output: false

Whether Player 1 first takes the 1 or the 2, Player 2 can respond so that Player 2 captures the 5, ending with a strictly higher total. Player 1 cannot force at least a tie.

Example 2

Input: nums = [1,5,233,7]

Output: true

Player 1 can secure the large 233 by playing the ends optimally, guaranteeing a final score that is at least as high as Player 2.

Constraints

  • 1 <= nums.length <= 20
  • 0 <= nums[i] <= 10^7
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now