Given a sequence of n real numbers A(1) ... A(n), determine a contiguous subsequence A(i) ... A(j) of length atleast L for which the sum of elements in the subsequence is maximized.
Set sumL to the sum of the first L array elements.
Set runningSum = sumL.
Set maxSum = sumL
For k = L + 1 up to n, the length of the array:
Set sumL = sumL + A(k) - A(k - L)
Set runningSum = max(runningSum + A(k), sumL)
Set maxSum = max(maxSum, runningSum)
Output maxSum
public class MaxContSumL {
public static void main(String[] args) {
int[] A = { 0, 5, -3, -1, 2, -4, -1, 7, 8 };
int L = 2;
maxContiguousSumOfLenAtleastL(A, L);
int[] B = { -5, -1, 2, -3, 0, -3, 3, };
L = 3;
maxContiguousSumOfLenAtleastL(B, L);
}
public static void maxContiguousSumOfLenAtleastL(int[] A, int L) {
int len = A.length;
int sumL = 0;
for (int i = 0; i < L; i++) {
sumL += A[i];
}
int runningSum = sumL;
int maxSum = sumL;
int start = 0, finish = 0;
for (int i = L; i < len; i++) {
sumL += (A[i] - A[i - L]);
runningSum = Math.max(runningSum + A[i], sumL);
if (runningSum > maxSum) {
maxSum = runningSum;
start = i - L + 1;
finish = i;
}
}
System.out.println("Max sum: " + maxSum);
System.out.println("Indices: i=" + start + " : j=" + finish);
}
}
No comments:
Post a Comment