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

#PS0000175. Tổng đoạn con lớn nhất trên vòng tròn (Maximum Sum Circular Subarray)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Tổng đoạn con lớn nhất trên vòng tròn (Maximum Sum Circular Subarray)

Maximum Sum Circular Subarray

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

Given a1,…,ana_1,\ldots,a_n arranged in a circle, with a1a_1 following ana_n, choose a starting position and a length between 1 and nn. Take consecutive elements in increasing index order, wrapping when necessary. Each array position may be selected at most once. Find the largest sum of a selected interval. Empty intervals are forbidden.

Input

The first line contains integer nn.

The second line contains the nn integers a1,…,ana_1,\ldots,a_n in order.

Output

Print one integer: the largest nonempty interval sum.

Subtasks

  • Subtask 1 (20 points): 1≤n≤5001\le n\le 500; −30000≤ai≤30000-30000\le a_i\le 30000.
  • Subtask 2 (30 points): 1≤n≤300001\le n\le 30000; 0≤ai≤300000\le a_i\le 30000.
  • Subtask 3 (50 points): 1≤n≤300001\le n\le 30000; −30000≤ai≤30000-30000\le a_i\le 30000.

Example 1

Input

4
1 -2 3 -2

Output

3

Explanation

Choose the element 3 alone. No longer interval has a sum exceeding 3.

Example 2

Input

3
5 -3 5

Output

10

Explanation

Choose positions 3 and 1 across the circular boundary; the sum is 10.

Example 3

Input

3
-3 -2 -3

Output

-2

Explanation

Choose -2 alone. The empty interval is not permitted.