Maximum Sum of a Circular Subarray

hard Arrays

Problem

The array is circular: after the last element comes the first one again. Find the biggest possible sum of a non-empty continuous part. The part may wrap around the end (it must not use any element twice). Print the sum. Hint: the best wrapping part is the total minus the smallest normal part.

Constraints

  • 1 <= n <= 10^5
  • |value| <= 10^4

Examples

Input

4
1 -2 3 -2

Output

3

Input

3
5 -3 5

Output

10

Solutions

Best approachTime O(n)Space O(1)

A part that wraps around is the whole array without one normal part in the middle. To make it as big as possible we remove the smallest normal part. The all-negative case needs care because removing everything would leave an empty part, which is not allowed.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Best circular sum.
 * Input   : n, then n integers.
 * Output  : The biggest sum.
 * Approach: Two Kadane runs.
 * Time    : O(n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static long solve(int[] a) {
        // Step 1: Run Kadane twice at the same time: once for the biggest sum and once for the smallest sum of a normal part.
        long total = a[0];
        long bestMax = a[0];
        long currentMax = a[0];
        long bestMin = a[0];
        long currentMin = a[0];
        for (int i = 1; i < a.length; i++) {
            total += a[i];
            currentMax = Math.max(currentMax + a[i], a[i]);
            bestMax = Math.max(bestMax, currentMax);
            currentMin = Math.min(currentMin + a[i], a[i]);
            bestMin = Math.min(bestMin, currentMin);
        }
        // Step 2: If all numbers are negative, the "total minus smallest part" would be empty, so use the normal answer.
        if (bestMax < 0) {
            return bestMax;
        }
        // Step 3: A wrapping part is everything except the smallest normal part.
        return Math.max(bestMax, total - bestMin);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        System.out.println(solve(a));
    }
}
Hints (1)
  1. Why is the all-negative case special?