Maximum Sum Circular Subarray
Given a circular array (the last element is connected to the first element), find the maximum contiguous subarray sum.
Constraints:
- 1 <= nums.length <= 10^4
- -10^5 <= nums[i] <= 10^5
Examples:
Input: [5,-3,5]
Output: 10
Explanation: The maximum sum is obtained by taking the subarray [5, -3, 5] which has a sum of 5 + (-3) + 5 = 7. However, since the array is circular, we can also consider the subarray [5, -3, 5] as [5] + [-3, 5] which has a sum of 5 + (-3 + 5) = 7. But the maximum sum is actually obtained by taking the subarray [5, -3, 5] as [-3, 5] + [5] which has a sum of (-3 + 5) + 5 = 7. So the maximum sum is 10 which is obtained by taking the subarray [5, -3, 5] as [5] + [5, -3].
Solutions
Kadane's Algorithm
The solution uses Kadane's algorithm to find the maximum sum of a subarray. It first calculates the maximum sum of a subarray using Kadane's algorithm. Then it calculates the maximum sum of a wrapped subarray by subtracting the minimum sum of a subarray from the total sum of the array.
int maxSubarraySumCircular(vector<int>& nums) {
int maxKadane = kadane(nums);
int maxWrapped = 0;
for (int i = 0;
i < nums.size();
i++) {
maxWrapped += nums[i];
}
int maxSum = maxWrapped;
for (int i = 0;
i < nums.size();
i++) {
maxWrapped -= nums[i];
maxSum = max(maxSum, maxWrapped);
}
return max(maxKadane, maxSum);
}
int kadane(vector<int>& nums) {
int maxSoFar = nums[0];
int maxEndingHere = nums[0];
for (int i = 1;
i < nums.size();
i++) {
maxEndingHere = max(nums[i], maxEndingHere + nums[i]);
maxSoFar = max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
Follow-up:
What if the array is not circular?