Skip to content

Commit

Permalink
Maximum Sum Circular Subarray Java Solution
Browse files Browse the repository at this point in the history
  • Loading branch information
Aarush2k1 authored Oct 5, 2022
1 parent fec7629 commit 28c24a2
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions LeetCode Solutions/918. Maximum Sum Circular Subarray.java
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;
}
}

0 comments on commit 28c24a2

Please sign in to comment.