All problems

Problem 41

Maximum Sum Circular Subarray

Medium · 20 pts · Array, Dynamic Programming

Problem

You are given a circular array of N integers: after the last element comes the first one again. Find the largest possible sum of a non-empty subarray, where a subarray may wrap around from the end back to the start, but may use each element at most once. The best subarray either does not wrap (the usual maximum subarray, found with Kadane's algorithm) or it wraps, in which case it is the whole array minus a minimum-sum middle block. So the answer is max(maxSubarray, total - minSubarray). The exception: if every element is negative, the answer is simply maxSubarray.

Input

First line: integer N. Second line: N space-separated integers.

Output

Print the maximum circular subarray sum.

Constraints

1 <= N <= 100000; -30000 <= A[i] <= 30000

Example input

3
5 -3 5

Example output

10

Explanation

In the circular array 5 -3 5, taking the last element 5 and wrapping around to the first element 5 gives 5 + 5 = 10, skipping the -3. That beats any non-wrapping subarray, so the answer is 10.

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

Previous: Pivot Index Next: First Missing Positive