
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.
#include <algorithm>
#include <numeric>
int kadane(const std::vector<int>& A) {
int current_max = A[0], max_so_far = A[0];
for (int i = 1; i < A.size(); i++) {
current_max = std::max(A[i], current_max + A[i]);
max_so_far = std::max(max_so_far, current_max);
}
return max_so_far;
}
int maxSubarraySumCircular(std::vector<int>& A) {
int sumAll = std::accumulate(A.begin(), A.end(), 0);
int max_normal = kadane(A);
for (auto& num : A) num = -num;
int max_circular = sumAll + kadane(A);
return max_circular == 0 ? max_normal : std::max(max_normal, max_circular);
}This solution utilizes C++ capabilities such as std::accumulate for array sum computation. The process involves finding the maximum normal subarray sum, altering the array for minimum subarray calculation utilizing a negated Kadane's algorithm, and in turn determining the potential maximum circular sum.
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 <stdio.h>
2
3int maxSubarraySumCircular(int* nums, int numsSize) {
4 int total = 0, max_sum = nums[0], min_sum = nums[0];
5 int cur_max = 0, cur_min = 0;
6
7 for (int i = 0; i < numsSize; i++) {
8 cur_max = cur_max + nums[i] > nums[i] ? cur_max + nums[i] : nums[i];
9 max_sum = max_sum > cur_max ? max_sum : cur_max;
10
11 cur_min = cur_min + nums[i] < nums[i] ? cur_min + nums[i] : nums[i];
12 min_sum = min_sum < cur_min ? min_sum : cur_min;
13
14 total += nums[i];
15 }
16
17 return max_sum < 0 ? max_sum : (max_sum > total - min_sum ? max_sum : total - min_sum);
18}This variation illustrates how a more verbose, manual evaluation of `max` and `min` decisions aids comprehension in languages like C. The algorithm operates by iterating through the numbers, updating cumulative totals and potential breaking points to determine the flexible subsequential approach.