PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#QHD0000016. Trò chơi lấy hai đầu (Deque)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Trò chơi lấy hai đầu (Deque)

Deque

Source: AtCoder

Version: Phuoc Hung OJ Extended

Problem Statement

Two players play a game with an ordered array of NN integers a1,a2,…,aNa_1,a_2,\ldots,a_N.

The first player moves first. On each turn, a player removes either the leftmost or the rightmost remaining element, adds its value to their own score, and leaves the other elements in their original order. The game ends when the array is empty.

Both players play optimally to maximize their score advantage. Compute the final score of the first player minus the score of the second player.

Input

The first line contains the integer NN, the number of elements.

The second line contains NN integers a1,a2,…,aNa_1,a_2,\ldots,a_N from left to right.

Output

Print the optimal score difference: first player’s score minus second player’s score. It may be negative.

Subtasks

  • Subtask 1 (20 points): 1≤N≤101\le N\le 10; 1≤ai≤1091\le a_i\le 10^9.
  • Subtask 2 (30 points): 1≤N≤1001\le N\le 100; 1≤ai≤1091\le a_i\le 10^9.
  • Subtask 3 (50 points): 1≤N≤30001\le N\le 3000; 1≤ai≤1091\le a_i\le 10^9.

Examples

Input

4
10 80 90 30

Output

10

Explanation

The first player takes 3030 from the right. From (10,80,90)(10,80,90), the opponent takes 9090 from the right; the first player then takes 8080 and the opponent gets 1010. The score difference is (30+80)−(90+10)=10(30+80)-(90+10)=10, the maximum guaranteed difference against optimal play.