Skip to content

Commit 6dcf770

Browse files
committed
Update documentation & testcases for maxSumCircularSubarray
1 parent 41ceee2 commit 6dcf770

File tree

3 files changed

+60
-46
lines changed

3 files changed

+60
-46
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ List of Programs related to data structures and algorithms
4848
| 7 | Sort Colors | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/7.sortColors/sortColors.js) | [Playground](https://livecodes.io/?console=open&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/7.sortColors/sortColors.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/7.sortColors/sortColors.md) | Medium | Two pointers |
4949
| 8 | Maximum product subarray | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/8.maxProductSubarray/maxProductSubarray.js) | [Playground](https://livecodes.io/?console=open&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/8.maxProductSubarray/maxProductSubarray.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/8.maxProductSubarray/maxProductSubarray.md) | Medium | Kadane's algorithm |
5050
| 9 | Find minimum in rotated sorted array | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/9.minRotatedSortedarray/minRotatedSortedarray.js) | [Playground](https://livecodes.io/?console=open&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/9.minRotatedSortedarray/minRotatedSortedarray.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/9.minRotatedSortedarray/minRotatedSortedarray.md) | Medium | Binary search technique |
51-
| 10 | Maximum Circular subarray | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/10.maxSumCircularSubArray/maxSumCircularSubArray.js) | [Playground](https://livecodes.io/?console=open&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/10.maxSumCircularSubArray/maxSumCircularSubArray.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/10.maxSumCircularSubArray/maxSumCircularSubArray.md) | Medium | Kadane's algorithm |
51+
| 10 | Maximum Circular subarray | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/10.maxSumCircularSubarray/maxSumCircularSubarray.js) | [Playground](https://livecodes.io/?console=open&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/10.maxSumCircularSubarray/maxSumCircularSubarray.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/10.maxSumCircularSubarray/maxSumCircularSubarray.md) | Medium | Kadane's algorithm |
5252
| 11 | Rotate array | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/11.rotateArray/rotateArray.js) | [Playground](https://livecodes.io/?console=open&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/11.rotateArray/rotateArray.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/11.rotateArray/rotateArray.md) | Medium | Two pointers |
5353
| 12 | Search in rotated sorted array | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/12.searchRotatedSortedArray/searchRotatedSortedArray.js) | [Playground](https://livecodes.io/?console=open&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/12.searchRotatedSortedArray/searchRotatedSortedArray.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/11.searchRotatedSortedArray/searchRotatedSortedArray.md) | Medium | Binary search |
5454
| 13 | Container with most water | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/13.containerWithMostWater/containerWithMostWater.js) | [Playground](https://livecodes.io/?console=open&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/13.containerWithMostWater/containerWithMostWater.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/13.containerWithMostWater/containerWithMostWater.md) | Medium | Two pointers |

src/javascript/algorithms/array/10.maxSumCircularSubarray/maxSumCircularSubarray.js

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,28 @@ function maxSumCircularSubarray(nums) {
77

88
for (const num of nums) {
99
currentMaxSum = Math.max(currentMaxSum + num, num);
10+
globalMaxSum = Math.max(currentMaxSum, globalMaxSum);
11+
1012
currentMinSum = Math.min(currentMinSum + num, num);
13+
globalMinSum = Math.min(currentMinSum, globalMinSum);
1114

1215
totalSum += num;
13-
14-
globalMaxSum = Math.max(currentMaxSum, globalMaxSum);
15-
globalMinSum = Math.min(currentMinSum, globalMinSum);
1616
}
1717

18+
// If all numbers are negative, total - globalMinSum would be 0 or less
1819
return globalMaxSum > 0 ? Math.max(globalMaxSum, (totalSum-globalMinSum)) : globalMaxSum;
1920
}
2021

21-
let numbers = [9, -9, 6, 11, -6, -10, 15, 1];
22-
console.log("Max circular subarray Sum:", maxSumCircularSubarray(numbers));
23-
24-
let numbers1 = [6,-2,6];
25-
console.log("Max circular subarray Sum:", maxSumCircularSubarray(numbers1));
26-
27-
let numbers2 = [-6,-2,-6];
28-
console.log("Max circular subarray Sum:", maxSumCircularSubarray(numbers2));
29-
30-
let emptyNumbers = [];
31-
console.log("Max circular subarray Sum:", maxSumCircularSubarray(emptyNumbers));
22+
// Test Cases
23+
// ---------------------------
24+
const testCases = [
25+
{ input: [9, -9, 6, 11, -6, -10, 15, 1], expected: 'Varies' },
26+
{ input: [6, -2, 6], expected: 12 },
27+
{ input: [-6, -2, -6], expected: -2 },
28+
{ input: [], expected: 0 }
29+
];
30+
31+
for (const { input, expected } of testCases) {
32+
const result = maxSumCircularSubarray(input);
33+
console.log(`Input: ${JSON.stringify(input)} => Max Circular Subarray Sum: ${result} (Expected: ${expected})`);
34+
}

src/javascript/algorithms/array/10.maxSumCircularSubarray/maxSumCircularSubarray.md

Lines changed: 42 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -13,34 +13,45 @@ Output: 12
1313
Input: nums = [-6,-2,-6]
1414
Output: -2
1515

16-
**Algorithmic Steps:**
17-
18-
This problem is solved with the help of **Kadane's algorithm**(dynamic programming technique), in which one time for finding the maximum subarray sum, and another time for finding the minimum subarray sum. The algorithmic approach can be summarized as follows:
19-
20-
1. Add a preliminary check for empty array and return 0 as a maximum sum.
21-
22-
2. Initialize overall maximum and minimum sum(i.e, `globalMaxSum` and `globalMinSum`) to first value of an input array.
23-
24-
**Note:** You shouldn't initialize global maximum and minimum values to zero because it results in wrong output for all negative elements usecase.
25-
26-
3. Initialize current maximum and minimum values(i.e, `currMaxSum` and `currMinSum`) of each iteration to zero.
27-
28-
4. Initialize total sum(`totalSum`) of all the elements to zero.
29-
30-
5. Iterate over an input array to calculate the maximum value.
31-
32-
6. Calculate the maximum and minimum sum at each element positon. The minimum sum is required to derive maximum value incase of circular subarray contains maximum value.
33-
34-
7. Find the total sum of all the numbers and store it in
35-
36-
8. Calculate the maximum and minimum sum found so far(`globalMaxSum` and `globalMinSum`) by comparing with current maximum and current minimum values.
37-
38-
9. Repeat steps 6-8 until all the elements traversed.
39-
40-
10. Return maximum of global maximum Sum and difference of total sum and globalMinSum, in case there are atleast one positive element. Otherwise return global maximum sum itself.
41-
42-
**Time and Space complexity:**
43-
44-
This algorithm has a time complexity of `O(n)`, where `n` is the number of elements. This is because we iterate the array at most once.
45-
46-
Here, we don't use any additional datastructure other than the few sum variables. Hence, the space complexity will be O(1).
16+
#### Algorithm Overview
17+
18+
This problem is solved using a **dual application of Kadane’s algorithm**, a dynamic programming technique commonly used to find the maximum subarray sum in linear time.
19+
20+
In a circular array, the maximum subarray sum is either:
21+
22+
1. The **maximum subarray sum** using the standard (non-circular) Kadane's algorithm.
23+
2. The **total array sum minus the minimum subarray sum** (which effectively gives the maximum sum of a wrapped subarray).
24+
25+
We compute both, and return the larger value.
26+
27+
#### Algorithm Steps
28+
29+
1. **Edge Case Check**
30+
If the input array is empty, return `0`.
31+
2. **Initialization**
32+
33+
* `globalMaxSum` and `globalMinSum` are both initialized to the first element of the array.
34+
* `currentMaxSum` and `currentMinSum` (used during iteration) are initialized to the same value.
35+
* `totalSum` is initialized to the first element of the array.
36+
37+
> ⚠️ _Note:_ Initializing `globalMaxSum` or `globalMinSum` to 0 instead of the first element would give incorrect results for arrays with all negative numbers.
38+
39+
3. **Traverse the Array**
40+
For each element in the array (starting from the second one):
41+
* Update `currentMaxSum = max(currentMaxSum + num, num)`
42+
* Update `globalMaxSum = max(globalMaxSum, currentMaxSum)`
43+
* Update `currentMinSum = min(currentMinSum + num, num)`
44+
* Update `globalMinSum = min(globalMinSum, currentMinSum)`
45+
* Accumulate `totalSum += num`
46+
4. **Final Result**
47+
* If all elements are negative, `globalMaxSum` will be the correct answer (since `totalSum - globalMinSum` would be 0).
48+
* Otherwise, return the maximum of:
49+
* `globalMaxSum` (standard Kadane’s)
50+
* `totalSum - globalMinSum` (circular case)
51+
52+
#### Time and Space Complexity
53+
54+
* **Time Complexity:** `O(n)`
55+
We iterate over the array exactly once.
56+
* **Space Complexity:** `O(1)`
57+
The algorithm uses a constant amount of extra space for tracking sums.

0 commit comments

Comments
 (0)