LeetCode 918 Maximum Sum Circular Subarray
it’s very similar to LC53 Maximum Sum Subarray.
but in this case, the maximum subarray can be in a whole, or exists in two points of array, the next graph can clearly represents the idea:
(图片转自lee215 from leetcode.com)
so we have two cases:
- the maxsubarray is the same as LC53
- the maximum results equals to the total sum - minmum subarray sum
so using the idea of dp, each time we mainly maintain four variables:
curMax: the curMax ends in current element
curMin: the curMin ends in current element
maxSum: the overall maximum
minSum: the overall minimum
and we only need to return the max of (maxSum, total_sum-min_sum).
but there is a conner case:
when all elements are negative, the: maxSum = max of all nums[]. and total_sum-min_sum = 0. and the max of those two elements must be 0, which means we choose the total_sum-min_sum, and that’s the total sum of empty array. but clearly, we can’t return an empty array of the results. so in this only case, we will return maxSum. so the code will be:
class Solution {
public int maxSubarraySumCircular(int[] A) {
int total = 0, maxSum = Integer.MIN_VALUE, curMax = 0, minSum = Integer.MAX_VALUE, curMin = 0;
for (int a : A) {
curMax = Math.max(curMax + a, a);
maxSum = Math.max(maxSum, curMax);
curMin = Math.min(curMin + a, a);
minSum = Math.min(minSum, curMin);
total += a;
}
return maxSum > 0 ? Math.max(maxSum, total - minSum) : maxSum; //we check if maxSum>0 or not, if it less than 0, then that means every element in A is negative
}
}

浙公网安备 33010602011771号