Skip to content

Commit 1e9fcda

Browse files
committed
Create 0918-maximum-sum-circular-subarray
1 parent ee7a3bc commit 1e9fcda

4 files changed

+95
-0
lines changed
+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package main
2+
3+
func main() {
4+
5+
}
6+
7+
func maxSubarraySumCircular(nums []int) int {
8+
globalMax, globalMin := nums[0], nums[0]
9+
currentMax, currentMin := 0, 0
10+
total := 0
11+
12+
for _, num := range nums {
13+
currentMax = max(num, currentMax+num)
14+
currentMin = min(num, currentMin+num)
15+
total += num
16+
globalMax = max(globalMax, currentMax)
17+
globalMin = min(globalMin, currentMin)
18+
}
19+
20+
if globalMax > 0 {
21+
return max(globalMax, total-globalMin)
22+
} else {
23+
return globalMax
24+
}
25+
26+
}
27+
28+
func max(a, b int) int {
29+
if a > b {
30+
return a
31+
}
32+
return b
33+
}
34+
35+
func min(a, b int) int {
36+
if a < b {
37+
return a
38+
}
39+
return b
40+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var maxSubarraySumCircular = function (nums) {
6+
let [globalMax, globalMin] = [nums[0], nums[0]];
7+
let [currentMax, currentMin] = [0, 0];
8+
let total = 0;
9+
10+
for (num of nums) {
11+
currentMax = Math.max(num, currentMax + num);
12+
currentMin = Math.min(num, currentMin + num);
13+
total += num;
14+
globalMax = Math.max(globalMax, currentMax);
15+
globalMin = Math.min(globalMin, currentMin);
16+
}
17+
18+
return globalMax > 0 ? Math.max(globalMax, total - globalMin) : globalMax;
19+
};
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
impl Solution {
2+
pub fn max_subarray_sum_circular(nums: Vec<i32>) -> i32 {
3+
let (mut global_max, mut global_min) = (nums[0], nums[0]);
4+
let (mut current_max, mut current_min) = (0, 0);
5+
let mut total = 0;
6+
7+
for num in nums {
8+
current_max = i32::max(num, current_max + num);
9+
current_min = i32::min(num, current_min + num);
10+
total += num;
11+
global_max = i32::max(global_max, current_max);
12+
global_min = i32::min(global_min, current_min);
13+
}
14+
15+
if global_max > 0 {
16+
return i32::max(global_max, total - global_min);
17+
} else {
18+
return global_max;
19+
}
20+
}
21+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
function maxSubarraySumCircular(nums: number[]): number {
2+
let [globalMax, globalMin] = [nums[0], nums[0]];
3+
let [currentMax, currentMin] = [0, 0];
4+
let total = 0;
5+
6+
for (let num of nums) {
7+
currentMax = Math.max(num, currentMax + num);
8+
currentMin = Math.min(num, currentMin + num);
9+
total += num;
10+
globalMax = Math.max(globalMax, currentMax);
11+
globalMin = Math.min(globalMin, currentMin);
12+
}
13+
14+
return globalMax > 0 ? Math.max(globalMax, total - globalMin) : globalMax;
15+
}

0 commit comments

Comments
 (0)