Maximum Contiguous Subsequence Sum of At Least Length L

后端 未结 5 1988
北海茫月
北海茫月 2020-12-01 01:53

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

5条回答
  •  旧时难觅i
    2020-12-01 02:11

    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;
    }
    

提交回复
热议问题