Skip to the code
cf.
+25 XP

#544 Card Row Duel

medium

In a browser card game, a row of cards with point values cards lies on the table. Two players take turns, and you go first. On each turn a player takes either the leftmost or the rightmost card and adds its points to their score. Both players always play as well as possible.

Write bestLead(cards) that returns your final score minus your opponent's final score.

Example 1

Input: cards = [4,1,7]
Output: 4

Take 7; the opponent takes 4; you take 1. That is 8 against 4.

Example 2

Input: cards = [1,5,2]
Output: -2

Whichever end you take, the opponent takes the 5: you get 3 and they get 5.

Constraints

  • 1 <= cards.length <= 1000
  • 0 <= cards[i] <= 1000
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).