#C7049. Maximum Rainfall in Subarray

    ID: 50877 Type: Default 1000ms 256MiB

Maximum Rainfall in Subarray

Maximum Rainfall in Subarray

You are given an integer N representing the total number of days, an integer K as the length of a contiguous subarray, and a list of N integers representing the amount of rainfall for each day. Your task is to determine the maximum total rainfall over any contiguous subarray of length K. If K > N, output -1.

This problem can be represented mathematically as follows. Given an array \(A[0 \dots N-1]\), find the maximum value of \[ S = \sum_{i=j}^{j+K-1} A[i] \] for any valid index j such that \(0 \leq j \leq N-K\), or return -1 if no such subarray exists.

Example: For input N = 10, K = 3 and rainfall amounts [6, 2, 9, 4, 1, 8, 3, 5, 7, 10], the maximum subarray sum is 22.

inputFormat

The first line contains two space-separated integers N and K representing the number of days and the subarray length, respectively. The second line contains N space-separated integers denoting the rainfall amounts for each day.

Constraints:

  • 1 \(\leq N \leq 10^5\)
  • 1 \(\leq K \leq 10^5\)
  • The rainfall amounts are integers.

outputFormat

Output a single integer representing the maximum sum of any contiguous subarray of length K if it exists. If K > N, output -1.

## sample
10 3
6 2 9 4 1 8 3 5 7 10
22