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

#GD0000051. Trò chuyện trong vòng tròn (Chat in a Circle)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Trò chuyện trong vòng tròn (Chat in a Circle)

Chat in a Circle

Source: AtCoder

Version: Phuoc Hung OJ Extended

Problem Statement

There are nn people with friendliness aia_i, arriving one by one and forming a circle. Each new arrival may insert anywhere. The first person receives comfort zero; each later arrival receives the smaller friendliness of the two adjacent people after insertion. Maximize total comfort.

Input

Line 1: nn. Line 2: nn friendliness values aia_i.

Output

Print the maximum total comfort.

Subtasks

  • Subtask 1 (20 points): 2≤n≤32\le n\le 3; 1≤ai≤1091\le a_i\le 10^9 for every ii.
  • Subtask 2 (30 points): 2≤n≤30002\le n\le 3000; 1≤ai≤1091\le a_i\le 10^9 for every ii.
  • Subtask 3 (50 points): 2≤n≤2000002\le n\le 200000; 1≤ai≤1091\le a_i\le 10^9 for every ii.

Examples

Input

4
2 2 1 3

Output

7

Explanation

Let friendliness 3 arrive first, then two people with friendliness 2 and the final person with friendliness 1. Appropriate insertions yield comforts 0, 3, 2, 2, totaling 7.