package leetcode;

/**
 * https://leetcode.com/problems/maximum-sum-circular-subarray/
 */
public class Problem918 {
    public int maxSubarraySumCircular(int[] A) {
        int answer = A[0];
        for (int i = 0; i < A.length; i++) {
            int sum = A[i];
            answer = Math.max(answer, sum);
            int j = (i + 1) % A.length;
            while (j != i) {
                sum += A[j];
                answer = Math.max(answer, sum);
                j = (j + 1) % A.length;
            }
        }
        return answer;
    }

    public static void main(String[] args) {
        Problem918 prob = new Problem918();
        System.out.println(prob.maxSubarraySumCircular(new int[]{1, -2, 3, -2})); // 3
        System.out.println(prob.maxSubarraySumCircular(new int[]{5, -3, 5})); // 10
        System.out.println(prob.maxSubarraySumCircular(new int[]{3, -1, 2, -1})); // 4
        System.out.println(prob.maxSubarraySumCircular(new int[]{3, -2, 2, -3})); // 3
        System.out.println(prob.maxSubarraySumCircular(new int[]{-2, -3, -1})); // -1
    }
}

@@ -175,236 +175,202 @@
 int 
-answer = A%5B0%5D;%0A        for (int i = 0; i %3C A.length; i++) %7B%0A            int sum = A%5Bi%5D;%0A            answer = Math.max(answer, sum);%0A            int j = (i + 1) %25 A.length;%0A            while (j != i) %7B%0A                sum += A%5Bj%5D
+total = 0;%0A        int maxSum = -30000;%0A        int maxSoFar = 0;%0A        int minSum = 30000;%0A        int minSoFar = 0;%0A        for (int a : A) %7B%0A            maxSoFar = Math.max(maxSoFar + a, a)
 ;%0A  
@@ -383,18 +383,14 @@
     
-    answer
+maxSum
  = M
@@ -401,635 +401,230 @@
 max(
-answer, sum);%0A                j = (j + 1) %25 A.length;%0A            %7D%0A        %7D%0A        return answer;%0A    %7D%0A%0A    public static void
+maxSum, maxSoFar);%0A            minSoFar = Math.min(minSoFar + a, a);%0A            minSum = Math.min(minSum,
  m
-a
 in
-(String%5B%5D args) %7B%0A        Problem918 prob = new Problem918();%0A        System.out.println(prob.maxSubarraySumCircular(new int%5B%5D%7B1, -2, 3, -2%7D)); // 3%0A        System.out.println(prob.maxSubarraySumCircular(new int%5B%5D%7B5, -3, 5%7D)); // 10%0A        System.out.println(prob.maxSubarraySumCircular(new int%5B%5D%7B3, -1, 2, -1%7D)); // 4%0A        System.out.println(prob.maxSubarraySumCircular(new int%5B%5D%7B3, -2, 2, -3%7D)); // 3%0A        System.out.println(prob.maxSubarraySumCircular(new int%5B%5D%7B-2, -3, -1%7D)); // -1
+SoFar);%0A            total += a;%0A        %7D%0A        return maxSum %3E 0 ? Math.max(maxSum, total - minSum) : maxSum;
 %0A   

Solve problem 918