forked from codemistic/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Maximum Sum Circular Subarray Java Solution
- Loading branch information
Showing
1 changed file
with
23 additions
and
0 deletions.
There are no files selected for viewing
23 changes: 23 additions & 0 deletions
23
LeetCode Solutions/918. Maximum Sum Circular Subarray.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
/* | ||
918. Maximum Sum Circular Subarray | ||
Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums. | ||
Input: nums = [1,-2,3,-2] | ||
Output: 3 | ||
https://leetcode.com/problems/maximum-sum-circular-subarray/ | ||
*/ | ||
|
||
class Solution { | ||
public int maxSubarraySumCircular(int[] A) { | ||
int total = 0, maxSum = A[0], curMax = 0, minSum = A[0], curMin = 0; | ||
for (int a : A) { | ||
curMax = Math.max(curMax + a, a); | ||
maxSum = Math.max(maxSum, curMax); | ||
curMin = Math.min(curMin + a, a); | ||
minSum = Math.min(minSum, curMin); | ||
total += a; | ||
} | ||
return maxSum > 0 ? Math.max(maxSum, total - minSum) : maxSum; | ||
} | ||
} |