Skip to lesson

A hard problem for practising 5.4 Array & String Techniques. Solve it in your own IDE, check it against every test, and open a hint only when you are stuck. 0/1 solved.

1. Best circular route profit

hard

A college shuttle runs on a ring road with n stops, numbered 1 to n. After stop n comes stop 1 again. At each stop the shuttle gains or loses some rupees: ticket money minus tolls and fuel.

The transport team can run one trip that starts at any stop and visits one or more consecutive stops in order, each stop at most once. A trip may pass stop n and continue from stop 1. Print the largest total the trip can earn. The trip must visit at least one stop, even if every stop loses money.

Input: The first line has one integer n. The second line has n integers: the gain at each stop, from stop 1 to stop n. A loss is a negative number.

Output: One integer: the largest total of one trip.

Limits: 1 ≤ n ≤ 10^5 · -10^9 ≤ gain ≤ 10^9

Example 1

Input

5
5 -3 -6 2 5

Output

12

Start at stop 4 and go round to stop 1: 2 + 5 + 5 = 12.

Example 2

Input

3
-3 -2 -5

Output

-2

Every stop loses money. The best trip is the single stop with -2.

Submit to solve