We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
int maxContiguous = Integer.MIN_VALUE;
int currSum = 0;
int maxNonContiguous = Integer.MIN_VALUE;
int nonContiguousSum = 0;
boolean hasPositive = false;
for (int num : arr) {
// Contiguous (Kadane’s algo): subarray
currSum = Math.max(num, currSum + num);
maxContiguous = Math.max(maxContiguous, currSum);
// Non-contiguous: subsequence
if (num > 0) {
nonContiguousSum += num;
hasPositive = true;
}
maxNonContiguous = Math.max(maxNonContiguous, num); // track max Element when all are negatives in list
}
if (!hasPositive) {
nonContiguousSum = maxNonContiguous; // in case all are negative
}
List<Integer> result = new ArrayList<>();
result.add(maxContiguous);
result.add(nonContiguousSum);
return result;
}
`
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
The Maximum Subarray
You are viewing a single comment's thread. Return to all comments →
`Java: Simple Code for Beginner:
public static List maxSubarray(List arr) {
} `