Skip to content

Commit 661bced

Browse files
committed
Add max sum circular subarray
1 parent c076a89 commit 661bced

File tree

6 files changed

+161
-32
lines changed

6 files changed

+161
-32
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,8 @@ List of Programs related to data structures and algorithms
6060
9. Find minimum in rotated sorted array: [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/9.minRotatedSortedarray/minRotatedSortedarray.js)
6161
[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)
6262

63-
10. Maximum Circular subarray: [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/maxCircularSubArray.js)
63+
10. Maximum Circular subarray: [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/10.maxSumCircularSubArray/maxSumCircularSubArray.js)
64+
[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)
6465

6566
11. Rotate array: [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/array/rotate.js)
6667

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package maxSumCircularSubarray;
2+
3+
public class MaxSumCircularSubarray {
4+
private static int maxSumCircularSubarray(int[] nums) {
5+
if(nums.length == 0) return 0;
6+
7+
int globalMaxSum = nums[0], globalMinSum = nums[0];
8+
int currMaxSum = 0, currMinSum = 0;
9+
int totalSum = 0;
10+
11+
for (int num : nums) {
12+
currMaxSum = Math.max(currMaxSum+num, num);
13+
currMinSum = Math.min(currMinSum+num, num);
14+
15+
totalSum += num;
16+
globalMaxSum = Math.max(globalMaxSum, currMaxSum);
17+
globalMinSum = Math.min(globalMinSum, currMinSum);
18+
}
19+
20+
return globalMaxSum > 0 ? Math.max(globalMaxSum, totalSum-globalMinSum) : globalMaxSum;
21+
}
22+
23+
public static void main(String[] args) {
24+
int[] nums1 = {9, -9, 6, 11, -6, -10, 15, 1};
25+
System.out.println(maxSumCircularSubarray(nums1));
26+
27+
int[] nums2 = {6,-2,6};
28+
System.out.println(maxSumCircularSubarray(nums2));
29+
30+
int[] nums3 = {-6,-2,-6};
31+
System.out.println(maxSumCircularSubarray(nums3));
32+
33+
int[] nums4 = {};
34+
System.out.println(maxSumCircularSubarray(nums4));
35+
}
36+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
**Description:**
2+
Given a circular integer array `nums` of length `n`, return the maximum possible sum of a non-empty subarray of `nums`.
3+
4+
### Examples
5+
Example 1:
6+
7+
Input: nums = [9, -9, 6, 11, -6, -10, 15, 1]
8+
Output: 33
9+
10+
Input: nums = [6,-2,6]
11+
Output: 12
12+
13+
Input: nums = [-6,-2,-6]
14+
Output: -2
15+
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 cirucular 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).
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
function maxSumCircularSubarray(nums) {
2+
if(nums.length === 0) return 0;
3+
4+
let globalMaxSum = nums[0], globalMinSum = nums[0];
5+
let currentMaxSum = 0, currentMinSum = 0;
6+
let totalSum = 0;
7+
8+
for (const num of nums) {
9+
currentMaxSum = Math.max(currentMaxSum + num, num);
10+
currentMinSum = Math.min(currentMinSum + num, num);
11+
12+
totalSum += num;
13+
14+
globalMaxSum = Math.max(currentMaxSum, globalMaxSum);
15+
globalMinSum = Math.min(currentMinSum, globalMinSum);
16+
}
17+
18+
return globalMaxSum > 0 ? Math.max(globalMaxSum, (totalSum-globalMinSum)) : globalMaxSum;
19+
}
20+
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));
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
**Description:**
2+
Given a circular integer array `nums` of length `n`, return the maximum possible sum of a non-empty subarray of `nums`.
3+
4+
### Examples
5+
Example 1:
6+
7+
Input: nums = [9, -9, 6, 11, -6, -10, 15, 1]
8+
Output: 33
9+
10+
Input: nums = [6,-2,6]
11+
Output: 12
12+
13+
Input: nums = [-6,-2,-6]
14+
Output: -2
15+
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 cirucular 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).

src/javascript/algorithms/array/maxCircularSubArray.js

-31
This file was deleted.

0 commit comments

Comments
 (0)