Ctrl K

Trim Pairs From the Ends

Medium
A row of cards with integers on them lies on the table: the array values. As long as more than two cards remain, you must make a move, removing exactly two cards in one of three ways: - the two leftmost cards; - the two rightmost cards; - the leftmost and the rightmost card. The sum of the removed cards is added to your score (numbers can be negative, so a move may lower it). Once one or two cards are left, the game is over. Return the highest score you can reach.
Example 1
values=[3, -5, 2, 6] → 9

Take the outer 3 and 6 (+9); [-5, 2] is left, only two elements, so the game ends. Total 9.

Example 2
values=[4, 9, -7] → 13

Taking the first two elements is best: 4 + 9 = 13, leaving -7 behind.

Example 3
values=[8] → 0

With a single element no move is possible, so the score is 0.

Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • -10⁴ ≤ values[i] ≤ 10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
loading Python…
Input
values=[3, -5, 2, 6]
Expected
9

Run checks the first 3 tests in your browser. Submit checks all 102 tests on the server, hidden ones included.