Skip to content

Commit 28c24a2

Browse files
authored
Maximum Sum Circular Subarray Java Solution
1 parent fec7629 commit 28c24a2

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/*
2+
918. Maximum Sum Circular Subarray
3+
4+
Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums.
5+
Input: nums = [1,-2,3,-2]
6+
Output: 3
7+
8+
https://leetcode.com/problems/maximum-sum-circular-subarray/
9+
*/
10+
11+
class Solution {
12+
public int maxSubarraySumCircular(int[] A) {
13+
int total = 0, maxSum = A[0], curMax = 0, minSum = A[0], curMin = 0;
14+
for (int a : A) {
15+
curMax = Math.max(curMax + a, a);
16+
maxSum = Math.max(maxSum, curMax);
17+
curMin = Math.min(curMin + a, a);
18+
minSum = Math.min(minSum, curMin);
19+
total += a;
20+
}
21+
return maxSum > 0 ? Math.max(maxSum, total - minSum) : maxSum;
22+
}
23+
}

0 commit comments

Comments
 (0)