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
.)
Example 1:
Input: [1,-2,3,-2] Output: 3 Explanation: Subarray [3] has maximum sum 3
Example 2:
Input: [5,-3,5] Output: 10 Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10
Example 3:
Input: [3,-1,2,-1] Output: 4 Explanation: Subarray [2,-1,3] has maximum sum 2 + (-1) + 3 = 4
Example 4:
Input: [3,-2,2,-3] Output: 3 Explanation: Subarray [3] and [3,-2,2] both have maximum sum 3
Example 5:
Input: [-2,-3,-1] Output: -1 Explanation: Subarray [-1] has maximum sum -1
Note:
-30000 <= A[i] <= 30000
1 <= A.length <= 30000
环形子数组的最大和。这个题一开始读题的时候让我觉得是53题的followup,但是这个题用53题DP的思想好像还不太能套用得上去,因为有可能最大的子数组是断开的。这个题我参考了lee大神的帖子。基本思路是因为input是环形的,所以有可能最后最大的子数组有可能是如下几种情形,如下图所示
- 一种是直接在原数组的中间
- 一种是在原数组前半段截取一点出来,在后半段也截取一点出来
对于第一种情况,其实就跟53题是一样的;但是对于第二种情况,如果我们需要得知断开的,最大的子数组,我们可以反过来去求连续的,最小的子数组的和,然后用整个数组的和 - 连续的,最小的子数组的和。唯一的corner case是如果整个数组都是由负数组成的,那么整个数组的和sum跟数组连续的,最小的子数组的和是一样的。最后比较的时候,需要看看到底是case 1的结果更大,还是case 2里面的min subarray更小。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public int maxSubarraySumCircular(int[] A) { 3 int total = 0; 4 // 全局的最大值 5 int maxSum = A[0]; 6 // 当前的最大值 7 int curMax = 0; 8 // 全局的最小值 9 int minSum = A[0]; 10 // 当前的最小值 11 int curMin = 0; 12 for (int a : A) { 13 curMax = Math.max(curMax + a, a); 14 maxSum = Math.max(maxSum, curMax); 15 curMin = Math.min(curMin + a, a); 16 minSum = Math.min(minSum, curMin); 17 total += a; 18 } 19 return maxSum > 0 ? Math.max(maxSum, total - minSum) : maxSum; 20 } 21 }
相关题目
918. Maximum Sum Circular Subarray