Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

Can the first player win?

Medium · Target 20 minutes · Dynamic programming · Type asked atGoogleCitadel

Two players take turns removing a number from either end of the list nums and adding it to their score. Both play optimally. Return true if the first player's final score is at least the second player's.

Examples

InputOutputWhy
nums = [1,5,2]falseWhichever end the first player takes, the second takes the 5.
nums = [1,5,233,7]trueTake 1; whatever comes next, the 233 is reachable.
nums = [7]trueTake it.

Constraints

  • 1 ≤ nums.length ≤ 20
  • 0 ≤ nums[i] ≤ 10⁷

Hints

Hint 1

Track the score difference, not both scores: diff(i, j) = the most the player to move can lead by on nums[i..j].

Hint 2

Taking nums[i] leaves the opponent to move on [i + 1, j]: nums[i] − diff(i + 1, j). Similarly for nums[j].

Hint 3

The first player wins or ties when diff(0, n − 1) ≥ 0.

Where people lose marks

  • Tracking both scores with greedy choices (taking the larger end is not optimal).
  • Treating a tie as a loss: the problem counts it as a win.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.