Algorithm
Problem Name: 918. Maximum Sum Circular Subarray
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 = [1,-2,3,-2] Output: 3 Explanation: Subarray [3] has maximum sum 3.
Example 2:
Input: nums = [5,-3,5] Output: 10 Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10.
Example 3:
Input: nums = [-3,-2,-3] Output: -2 Explanation: Subarray [-2] has maximum sum -2.
Constraints:
n == nums.length
1 <= n <= 3 * 104
-3 * 104 <= nums[i] <= 3 * 104
Code Examples
#1 Code Example with Javascript Programming
Code -
Javascript Programming
const maxSubarraySumCircular = function(A) {
let minSum = Infinity, sum = 0, maxSum = -Infinity, curMax = 0, curMin = 0
for(let a of A) {
sum += a
curMax = Math.max(curMax + a, a);
maxSum = Math.max(maxSum, curMax);
curMin = Math.min(curMin + a, a);
minSum = Math.min(minSum, curMin);
}
return maxSum > 0 ? Math.max(maxSum, sum - minSum) : maxSum;
};
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Python Programming
Code -
Python Programming
class Solution:
def maxSubarraySumCircular(self, A):
lMn, rMx, res, lSm, rSm, preSm = float("inf"), [-float("inf")] * (len(A) + 1), -float("inf"), 0, 0, 0
for i in range(len(A) - 1, -1, -1):
rSm += A[i]
rMx[i] = max(rMx[i + 1], rSm)
for i in range(len(A)):
preSm += A[i]
lMn = min(lMn, lSm)
res = max(res, preSm, preSm - lMn, preSm + rMx[i + 1])
lSm += A[i]
return res
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with C# Programming
Code -
C# Programming
using System;
using System.Linq;
namespace LeetCode
{
public class _0918_MaximumSumCircularSubarray
{
public int MaxSubarraySumCircular(int[] A)
{
int n = A.Length;
if (n == 1) return A[0];
int curr = int.MinValue, result1 = int.MinValue;
for (int i = 0; i < n; i++)
{
curr = A[i] + Math.Max(curr, 0);
result1 = Math.Max(result1, curr);
}
int total = A.Sum();
curr = int.MaxValue;
int result2 = int.MaxValue;
for (int i = 1; i < n; i++)
{
curr = A[i] + Math.Min(curr, 0);
result2 = Math.Min(result2, curr);
}
result2 = total - result2;
curr = int.MaxValue;
int result3 = int.MaxValue;
for (int i = 0; i < n - 1; i++)
{
curr = A[i] + Math.Min(curr, 0);
result3 = Math.Min(result3, curr);
}
result3 = total - result3;
return Math.Max(result1, Math.Max(result2, result3));
}
}
}
Copy The Code &
Try With Live Editor
Input
Output