All problems

Problem 463

Optimal Strategy for a Coin Game

Medium · 20 pts · Array, Dynamic Programming, Game Theory

Problem

N coins lie in a row (N is even). Two players take turns, and on each turn a player removes either the first or the last coin of the row and keeps its value. Both players play optimally, each trying to maximise their own total. Print the maximum total the first player can guarantee. Let best[i][j] be the most the player to move can collect from coins i..j; they take one end, and then the opponent plays optimally on what remains.

Input

First line: N (even). Second line: the N coin values.

Output

Print the first player's maximum guaranteed total.

Constraints

2 <= N <= 1000; N is even; 1 <= value <= 1000000

Example input

4
5 3 7 10

Example output

15

Explanation

For 5 3 7 10, the first player takes 10; the second player then takes 7; the first takes 5; the second takes 3. The first player gets 15, the most they can guarantee.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Minimum Cost to Cut a Stick Next: Weighted Job Scheduling