
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 // Calculate total sum of the array
6 for (int a : A) {
7 sumAll += a;
8 }
9
10 // Standard Kadane's Algorithm for the maximum subarray sum
11 int currentMax = A[0], maxSoFar = A[0];
12 for (int i = 1; i < A.length; i++) {
13 currentMax = Math.max(A[i], currentMax + A[i]);
14 maxSoFar = Math.max(maxSoFar, currentMax);
15 }
16
17 // Modified Kadane's to find minimum so far
18 int currentMin = A[0], minSoFar = A[0];
19 for (int i = 1; i < A.length; i++) {
20 currentMin = Math.min(A[i], currentMin + A[i]);
21 minSoFar = Math.min(minSoFar, currentMin);
22 }
23
24 int max_circular = sumAll - minSoFar;
25
26 return max_circular == 0 ? maxSoFar : Math.max(maxSoFar, max_circular);
27 }
28}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#
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.