You are given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums.
A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n].
A subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j], there does not exist i <= k1, k2 <= j with k1 % n == k2 % n.
Example 1:
Input: nums = [-2,4,-5,4,-5,9,4]
Output: 15Explanation: Subarray [-2,4,9,4] has maximum sum 15.
Example 2:
Input: nums = [2,3,-4]
Output: 5Constraints:
n == nums.length1 <= n <= 3 * 10,000-30,000 <= nums[i] <= 30,000class Solution:
def maxSubarraySumCircular(self, nums: List[int]) -> int:
n = len(nums)
res = nums[0]
for i in range(n):
cur_sum = 0
for j in range(i, i + n):
cur_sum += nums[j % n]
res = max(res, cur_sum)
return resclass Solution:
def maxSubarraySumCircular(self, nums: List[int]) -> int:
n = len(nums)
right_max = [0] * n
right_max[-1] = nums[-1]
suffix_sum = nums[-1]
for i in range(n - 2, -1, -1):
suffix_sum += nums[i]
right_max[i] = max(right_max[i + 1], suffix_sum)
max_sum = nums[0]
cur_max = 0
prefix_sum = 0
for i in range(n):
cur_max = max(cur_max, 0) + nums[i]
max_sum = max(max_sum, cur_max)
prefix_sum += nums[i]
if i + 1 < n:
max_sum = max(max_sum, prefix_sum + right_max[i + 1])
return max_sumclass Solution:
def maxSubarraySumCircular(self, nums: List[int]) -> int:
globMax, globMin = nums[0], nums[0]
curMax, curMin = 0, 0
total = 0
for num in nums:
curMax = max(curMax + num, num)
curMin = min(curMin + num, num)
total += num
globMax = max(globMax, curMax)
globMin = min(globMin, curMin)
return max(globMax, total - globMin) if globMax > 0 else globMax