LeetCode Solutions
918. Maximum Sum Circular Subarray
Time: Space:
class Solution {
public:
int maxSubarraySumCircular(vector<int>& A) {
int totalSum = 0;
int currMaxSum = 0;
int currMinSum = 0;
int maxSum = INT_MIN;
int minSum = INT_MAX;
for (int a : A) {
totalSum += a;
currMaxSum = max(currMaxSum + a, a);
currMinSum = min(currMinSum + a, a);
maxSum = max(maxSum, currMaxSum);
minSum = min(minSum, currMinSum);
}
return maxSum < 0 ? maxSum : max(maxSum, totalSum - minSum);
}
};
class Solution {
public int maxSubarraySumCircular(int[] A) {
int totalSum = 0;
int currMaxSum = 0;
int currMinSum = 0;
int maxSum = Integer.MIN_VALUE;
int minSum = Integer.MAX_VALUE;
for (int a : A) {
totalSum += a;
currMaxSum = Math.max(currMaxSum + a, a);
currMinSum = Math.min(currMinSum + a, a);
maxSum = Math.max(maxSum, currMaxSum);
minSum = Math.min(minSum, currMinSum);
}
return maxSum < 0 ? maxSum : Math.max(maxSum, totalSum - minSum);
}
}
class Solution:
def maxSubarraySumCircular(self, A: List[int]) -> int:
totalSum = 0
currMaxSum = 0
currMinSum = 0
maxSum = -math.inf
minSum = math.inf
for a in A:
totalSum += a
currMaxSum = max(currMaxSum + a, a)
currMinSum = min(currMinSum + a, a)
maxSum = max(maxSum, currMaxSum)
minSum = min(minSum, currMinSum)
return maxSum if maxSum < 0 else max(maxSum, totalSum - minSum)