Advertisement
1988coder

918. Maximum Sum Circular Subarray

Feb 3rd, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.67 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/maximum-sum-circular-subarray/
  2.  
  3. /**
  4.  * Kadane's Algorithm.
  5.  *
  6.  * Refer: (Very Good Explanation)
  7.  * https://leetcode.com/problems/maximum-sum-circular-subarray/discuss/178422/One-Pass
  8.  *
  9.  * So there are two cases.
  10.  *
  11.  * 1.The result subarray is the middle part. In this case maxSoFar should give
  12.  * the answer.
  13.  *
  14.  * 2. The subarray takes a part of head array and a part of tail array. The
  15.  * maximum result equals to totalSum minus minSoFar.
  16.  *
  17.  * So the max subarray circular sum equals to max(maxSoFar, totalSum - minSoFar)
  18.  *
  19.  * Corner case: If all number are negative, return the maximum one, (which
  20.  * equals to maxSoFar)
  21.  *
  22.  * Time Complexity: O(N)
  23.  *
  24.  * Space Complexity: O(1)
  25.  *
  26.  * N = Length of the input array.
  27.  */
  28. class Solution {
  29.     public int maxSubarraySumCircular(int[] A) throws IllegalArgumentException {
  30.         if (A == null || A.length == 0) {
  31.             throw new IllegalArgumentException("Invalid input. Input array is null or empty");
  32.         }
  33.         if (A.length == 1) {
  34.             return A[0];
  35.         }
  36.  
  37.         int maxEndingHere = A[0];
  38.         int maxSoFar = A[0];
  39.  
  40.         int minEndingHere = A[0];
  41.         int minSoFar = A[0];
  42.  
  43.         int sum = A[0];
  44.  
  45.         for (int i = 1; i < A.length; i++) {
  46.             maxEndingHere = Math.max(maxEndingHere + A[i], A[i]);
  47.             maxSoFar = Math.max(maxSoFar, maxEndingHere);
  48.  
  49.             minEndingHere = Math.min(minEndingHere + A[i], A[i]);
  50.             minSoFar = Math.min(minSoFar, minEndingHere);
  51.  
  52.             sum += A[i];
  53.         }
  54.  
  55.         return maxSoFar <= 0 ? maxSoFar : Math.max(maxSoFar, sum - minSoFar);
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement