Given array of integers, find the maximal possible sum of some of its k consecutive elements.

Example

For inputArray = [2, 3, 5, 1, 6] and k = 2, the output should be

solution(inputArray, k) = 8.

All possible sums of 2 consecutive elements are:

Input/Output

풀이

int solution(int[] inputArray, int k) {
    int result = Integer.MIN_VALUE;
    
    for (int i = 0; i <= inputArray.length - k; i ++) {
        int sum = 0;
        
        for (int j = i; j < i + k; j ++) {
            sum += inputArray[j];
        }
        
        if (result < sum) result = sum;
    }
    
    return result;
}