918. Maximum Sum Circular Subarray
Problem description:
Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty subarray of C.
Here, a circular array means the end of the array connects to the beginning of the array. (Formally, C[i] = A[i] when 0 <= i < A.length, and C[i+A.length] = C[i] when i >= 0.)
Also, a subarray may only include each element of the fixed buffer A at most once. (Formally, for a subarray C[i], C[i+1], …, C[j], there does not exist i <= k1, k2 <= j with k1 % A.length = k2 % A.length.)
1 | Example 1: |
1 | Example 2: |
1 | Example 3: |
1 | Example 4: |
1 | Example 5: |
Note:
-30000 <= A[i] <= 30000
1 <= A.length <= 30000
Solution:
This is a followup question of 53. Maximum Subarray. We can use a similar idea to solve it.
The idea is to remove the biggest negative sum in the array. Then the rest of the elements are the maximum sum in a continuous way.
Idea:
The result will have the following two different cases.
For example:
[2,3,-6,-7,4,5]
total sum= 1: 2+3+4+5= 14, -6+(-7)= -13
that is to say, if we can find the elements we want to remove, then we can get the maximum continuous sum.
- Calculate the maximum continuous sum,
nocircle
, of the original array. If thenocircle
is negative, it means all the elements in the array is negative. Therefore, just return the largest negative element. Which is -1 in the above example. - Sum up the array, and multiply each element with
-1
in the mean time. By doing this, we can use the same help function to get the smallest continuous sum in the original array, which is[6,7]
in above example. - Compare the
nocircle
andcircle
, return the maximum one.
1 | class Solution { |
Solution One pass:
We can further optimize the code with four variables to record the current minimum/maximum, all tim minimum/maximum as shown below.
1 | class Solution { |
time complexity: $O(n)$
space complexity: $O(1)$
reference:
https://www.geeksforgeeks.org/maximum-contiguous-circular-sum/
https://goo.gl/na2uyB