
Sponsored
Sponsored
The main idea is to use Kadane's Algorithm to find the maximum subarray sum for two scenarios: one, where the subarray wraps around the end and beginning of the array, and two, where it does not.
Calculate the maximum subarray sum using Kadane's algorithm in the normal way. Then calculate the minimum subarray sum using a similar technique but by negating the result. The maximum possible circular subarray sum will be the maximum value between the normal subarray sum and the total array sum minus the minimum subarray sum.
Time Complexity: O(n) — as both the applications of Kadane's algorithm are linear.
Space Complexity: O(1) — no additional space is used except for a few variables.
1public class Solution {
2 public int maxSubarraySumCircular(int[] A) {
3 int sumAll = 0;
4
5
This Java solution defines a method to compute the maximum sum of a circular subarray. By determining the total sum, applying Kadane's algorithm to find both the maximum subarray and the minimum (using negation) subarray, it calculates the potential maximum circular subarray sum and returns the maximum possible value.
Instead of using basic Kadane's approach, we can consider computing the maximum subarray sum with additional memory for storing maximum and minimum values up to each index. This allows precise tracing of subarrays—as contiguous and potential wrap-around cases.
Time Complexity: O(n)
Space Complexity: O(1)
1#include <vector>
#include <algorithm>
int maxSubarraySumCircular(std::vector<int>& nums) {
int total = 0, max_sum = nums[0], min_sum = nums[0];
int cur_max = 0, cur_min = 0;
for (int num : nums) {
cur_max = std::max(cur_max + num, num);
max_sum = std::max(max_sum, cur_max);
cur_min = std::min(cur_min + num, num);
min_sum = std::min(min_sum, cur_min);
total += num;
}
return (max_sum < 0) ? max_sum : std::max(max_sum, total - min_sum);
}Through utilizing the flexibility of C++ built-in methods, we solve the problem by maintaining totals and conditionally updating minimum and maximum traversal outcomes. This efficiently constructs results to verify and return at the term end.