Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray [4,−1,2,1] has the largest sum = 6.
Kadane’s Algorithm:
Initialize:
max_so_far = 0
max_ending_here = 0
Loop for each element of the array
(a) max_ending_here = max_ending_here + a[i]
(b) if(max_ending_here < 0)
max_ending_here = 0
(c) if(max_so_far < max_ending_here)
max_so_far = max_ending_here
return max_so_far
public int maxSubArray(int[] A) {
if (A==null || A.length==0) {
return 0;
}
int largestNegative = checkIfAllNegatives(A);
if (largestNegative<0) {
return largestNegative;
}
//sum is to track the max sum
int sum = 0;
//sumEndHere is used to track positive sums
int sumEndHere = 0;
for (int i=0; i<A.length; i++) {
sumEndHere += A[i];
if (sumEndHere<0) {
sumEndHere = 0;
} else if (sum<sumEndHere) {
sum = sumEndHere;
}
}
return sum;
}
public int checkIfAllNegatives(int[] A) {
int largestNegative = Integer.MIN_VALUE;
for (int i=0; i<A.length; i++) {
if (A[i]>=0) {
return 0;
} else {
if (largestNegative < A[i]) {
largestNegative = A[i];
}
}
}
return largestNegative;
}
DP: We should ignore the sum of the previous n-1 elements if nth element is greater than the sum.
public int maxSubArrayDP(int[] A) {
if (A==null || A.length==0) {
return 0;
}
int maxSoFar = A[0];
int sumSoFar = A[0];
for (int i=1; i<A.length; i++) {
sumSoFar = Math.max(A[i], sumSoFar+A[i]);
maxSoFar = Math.max(maxSoFar, sumSoFar);
}
return maxSoFar;
}