So for the following array, where L = 3
-5 -1 2 -3 0 -3 3
The best possible sum of at least length 3 would be 0, where the subsequence is t
Below is my Java implementation.
public static int maxSumSubsequenceGivenLength(int[] array, int l) {
if (null == array || array.length < l) {
return -1;
}
int previousSequenceSum = 0;
for (int i = 0; i < l; i++) {
previousSequenceSum += array[i];
}
int maxSum = previousSequenceSum;
int currentSum = 0;
int startIndexFinal = 0;
int endIndexFinal = l - 1;
for (int i = l; i < array.length; i++) {
currentSum = previousSequenceSum + array[i] - array[i - l];
if (currentSum > maxSum) {
maxSum = currentSum;
endIndexFinal = i;
startIndexFinal = i - l + 1;
}
previousSequenceSum = currentSum;
}
System.out.println("start index:" + startIndexFinal + " end index: " + endIndexFinal);
return maxSum;
}