826. Grab Up to Double

Two archivists share a shelf of boxes, piles[i] being the number of documents in box i. They alternate, you first. A limit M starts at 1. On a turn the mover takes the first X boxes still on the shelf for any 1 <= X <= 2*M and then M becomes max(M, X). The game ends when the shelf is empty.

Both play perfectly to maximise their own document total. Return the largest number of documents you can guarantee for yourself.

Aim for time O(n^3) and space O(n^2), where n is the number of boxes.

Example 1

Input:
piles = [7,3,12,5,9,2]
Output:
23
Explanation:

Starting with the first two piles (10 stones) leaves the opponent facing a limit of 2; the best total you can force is 22 of the 38 stones.

Example 2

Input:
piles = [4,15,6]
Output:
19
Explanation:

Taking the first two boxes gives 19 and leaves only the 6 for the opponent; taking just one box would let the opponent sweep the other two.

Constraints

1 ≤ piles.length ≤ 200

1 ≤ piles[i] ≤ 10000

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n^3)
Space
O(n^2)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…