
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.
1function maxSubarraySumCircular(A) {
2 const kadane = (arr) => {
3 let current = arr[0];
4 let maxSum = arr[0];
5 for (let i = 1; i < arr.length; i++) {
6 current = Math.max(arr[i], current + arr[i]);
7 maxSum = Math.max(maxSum, current);
8 }
9 return maxSum;
10 };
11
12 const totalSum = A.reduce((a, b) => a + b, 0);
13 const maxNormal = kadane(A);
14
15 // Invert signs of array elements for min kadane
16 for (let i = 0; i < A.length; i++) A[i] = -A[i];
17 const maxCircular = totalSum + kadane(A);
18
19 return maxCircular === 0 ? maxNormal : Math.max(maxNormal, maxCircular);
20}The JavaScript solution uses a concise and functional approach, relying on helper function kadane within the maxSubarraySumCircular function. It computes the normal and circular max subarrays, handling potential negatives through transformation and comparison of the sum results.
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
In this dynamic programming approach, two critical values are maintained: the current maximum and minimum subarray sums found. We update each possibility as we iterate across elements and calculate the total array sum to assist in determining potential circular maximum subarrays later.