Coin Game

Time limit1sMemory limit32 MB

Summary
Two players alternately take coins from the top of a pile, where each move may take between 1 and twice the previous move's count; find the maximum total value the first player can guarantee with optimal play from both sides.
Level

Hard8 of 10

Topics
Dynamic programming, Game theory, Greedy, Prefix sum
Solved
No attempts yet

Problem

Two players take turns in a coin game.

Initially NN coins are stacked in a single pile. The ii-th coin from the top has value CiC_i.

The first player takes one or two coins from the top of the pile. On every turn after that, a player may take at most twice as many coins as the previous player just took, and must take at least one. In other words, if the previous player took kk coins, the current player may take from 11 up to 2k2k coins from the top. (If fewer coins remain, they take only what is left.) The game ends when no coins remain.

Both players act optimally to maximize the total value of the coins they collect. Assuming the second player also plays to maximize their own total, find the maximum total value the first player can collect.

Input

The first line contains the number of coins NN (5≤N≤20005 \le N \le 2000).

Each of the next NN lines contains CiC_i, the value of the ii-th coin from the top (1≤Ci≤1000001 \le C_i \le 100000).

Output

Print the maximum total value the first player can collect.

Hint

Consider coins whose values from top to bottom are 1,3,1,7,21, 3, 1, 7, 2.

The first player takes one coin (value 11). The second player also takes one coin (value 33). The first player then takes two coins (values 1,71, 7, total 99). Finally the second player takes the remaining coin (value 22, total 55). The first player's collected value of 99 is the maximum.

Examples1

  1. Example 1

    Input
    5
    1
    3
    1
    7
    2
    
    Expected output
    9