#918
Maximum Sum Circular Subarray
MediumArrayDivide and ConquerDynamic ProgrammingQueueMonotonic QueueKadane's AlgorithmDynamic ProgrammingSliding Window
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages Kadane's algorithm to find the maximum sum of a non-circular subarray and the maximum sum of a circular subarray by calculating the total sum and the minimum subarray sum. The result is the maximum of these two values.
⚙️
Algorithm
5 steps- 1Step 1: Use Kadane's algorithm to find the maximum subarray sum (max_kadane).
- 2Step 2: Calculate the total sum of the array.
- 3Step 3: Use Kadane's algorithm to find the minimum subarray sum (min_kadane).
- 4Step 4: Calculate the maximum circular sum as total_sum - min_kadane.
- 5Step 5: Return the maximum of max_kadane and max_circular_sum, ensuring to handle cases where all numbers are negative.
solution.py13 lines
1def maxSubarraySumCircular(nums):
2 def kadane(arr):
3 max_sum = current_sum = arr[0]
4 for num in arr[1:]:
5 current_sum = max(num, current_sum + num)
6 max_sum = max(max_sum, current_sum)
7 return max_sum
8
9 max_kadane = kadane(nums)
10 total_sum = sum(nums)
11 min_kadane = kadane([-num for num in nums])
12 max_circular = total_sum + min_kadane
13 return max(max_kadane, max_circular) if max_kadane > 0 else max_kadaneℹ
Complexity note: This complexity is linear because we only traverse the array a constant number of times (twice in total) to calculate the maximum and minimum subarray sums.
- 1Kadane's algorithm is a powerful technique for finding maximum subarray sums efficiently.
- 2Circular subarrays can be handled by considering both the maximum non-circular and circular cases.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.