Problem Description
Given a circular integer array nums, return the maximum possible sum of a non-empty subarray. A circular array means that the end of the array connects to the beginning. The subarray can only include each element at most once.
Key Insights
- Use Kadane's algorithm to find the maximum sum of a contiguous non-circular subarray.
- Apply a modified Kadane's algorithm to find the minimum subarray sum.
- The maximum circular subarray sum can be computed as (total sum of array - minimum subarray sum).
- Handle the edge case where all numbers are negative by returning the non-circular maximum.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
The solution involves two passes over the array. In the first pass, we apply Kadane’s algorithm to find the maximum subarray sum. In the second pass, we compute the minimum subarray sum using a similar approach. The maximum circular subarray sum is then the maximum of the non-circular (standard) maximum or (total sum - minimum subarray sum). However, if all numbers are negative, the non-circular maximum is returned to avoid an incorrect result caused by subtracting the minimum subarray sum.