Untitled
unknown
plain_text
a year ago
757 B
4
Indexable
public class MaxCircularSubarraySum {
public int maxSubarraySumCircular(int[] nums) {
int maxKadane = kadane(nums); // Maximum sum of non-circular subarray
int totalSum = 0;
for (int num : nums) {
totalSum += num; // Total sum of the array
}
int minKadane = kadaneMin(nums); // Minimum sum of a subarray
// If totalSum is equal to minKadane, this means all elements are negative
// and removing any subarray would not give us a valid circular subarray.
if (totalSum == minKadane) {
return maxKadane;
}
// The result will be the maximum of non-circular max and circular sum
return Math.max(maxKadane, totalSum - minKadane);
}Editor is loading...
Leave a Comment