#K51912. Subarray Sums
Subarray Sums
Subarray Sums
Given an array of N integers and a number K, compute the sum of every contiguous subarray of length K. A contiguous subarray is defined as a sequence of consecutive elements in the array. Use the sliding window technique to achieve an efficient solution.
In mathematical terms, if the array is \(a_0, a_1, \ldots, a_{N-1}\), you are to calculate:
\[ S_i = \sum_{j=i}^{i+K-1} a_j \quad \text{for} \quad i = 0, 1, \ldots, N-K \]If \(K > N\) or \(K \le 0\), then no valid subarray exists and nothing should be output.
inputFormat
The input is given via standard input (stdin) and consists of two lines:
- The first line contains two space-separated integers \(N\) and \(K\), where \(N\) is the number of elements in the array and \(K\) is the length of each subarray.
- The second line contains \(N\) space-separated integers representing the elements of the array.
outputFormat
Output the sums of all contiguous subarrays of length \(K\) in a single line, separated by a single space. If no valid subarray exists (i.e. if \(K > N\) or \(K \le 0\)), output nothing.
## sample8 3
1 2 3 4 5 6 7 8
6 9 12 15 18 21