
Sponsored
Sponsored
The main idea is to use Kadane's Algorithm to find the maximum subarray sum for two scenarios: one, where the subarray wraps around the end and beginning of the array, and two, where it does not.
Calculate the maximum subarray sum using Kadane's algorithm in the normal way. Then calculate the minimum subarray sum using a similar technique but by negating the result. The maximum possible circular subarray sum will be the maximum value between the normal subarray sum and the total array sum minus the minimum subarray sum.
Time Complexity: O(n) — as both the applications of Kadane's algorithm are linear.
Space Complexity: O(1) — no additional space is used except for a few variables.
1def maxSubarraySumCircular(nums):
2 def kadane(gen):
3 current = result = nums[0]
4 for x in gen:
5 current = x + max(current, 0)
6 result = max(result, current)
7 return result
8
9 s = sum(nums)
10 max_normal = kadane(nums)
11 max_circular = s + kadane(-x for x in nums[1:])
12
13 if max_circular == 0:
14 return max_normal
15 return max(max_normal, max_circular)The function kadane is a helper function designed to employ Kadane's algorithm for any iterable. It efficiently finds the maximum sum of a contiguous subarray.
We then calculate the total sum of the array and determine the maximum subarray sum using Kadane's. By reversing the signs of the array elements and applying Kadane's algorithm again, we effectively discover the minimum subarray sum. The maximum sum is then checked against two cases:
Instead of using basic Kadane's approach, we can consider computing the maximum subarray sum with additional memory for storing maximum and minimum values up to each index. This allows precise tracing of subarrays—as contiguous and potential wrap-around cases.
Time Complexity: O(n)
Space Complexity: O(1)
1def
In this dynamic programming approach, two critical values are maintained: the current maximum and minimum subarray sums found. We update each possibility as we iterate across elements and calculate the total array sum to assist in determining potential circular maximum subarrays later.