Ctrl K

Duel for the End Heaps

Medium
Heaps of coins lie on a table in a row; heaps[i] is the number of coins in heap i. There is an even number of heaps and an odd total of coins, so a tie is impossible. Two players take turns, the first player moving first. On a turn, a player takes one whole heap, either the leftmost or the rightmost one still on the table. When the heaps run out, whoever holds more coins wins. Both play optimally. Return True if the first player wins and False if the second player does.
Example 1
heaps=[2, 9, 4, 2] → True

The first player takes the right heap of 2. That leaves [2, 9, 4], and whichever end the opponent takes (2 or 4), the 9 opens up. The final score is 2 + 9 = 11 against 6.

Example 2
heaps=[7, 2] → True

The first player takes the 7 right away and wins 7 to 2.

Example 3
heaps=[3, 1, 5, 4, 2, 6] → True
Constraints
  • 2 ≤ len(heaps) ≤ 500
  • len(heaps) is even
  • 1 ≤ heaps[i] ≤ 500
  • sum(heaps) is odd
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsDuel for the End Cards MediumThe Growing Grab Limit MediumScoring What Remains MediumTake From Any Pile MediumGrab Up to Three Cards Hard
loading Python…
Input
heaps=[2, 9, 4, 2]
Expected
True

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