Sum of Elements in Window
EasyPractice library · +10 XPsliding windowarrays
Given an array of N integers and an integer K, find the sum of all contiguous subarrays of size K. For each possible starting position of a subarray of size K, calculate its sum and print it. The subarrays should be processed from left to right.
Input
The first line contains two integers N and K, separated by a space. The second line contains N integers, the elements of the array.
Output
Print N-K+1 integers, where each integer is the sum of a subarray of size K. The sums should be printed on a single line, separated by spaces.
Constraints
1 <= K <= N <= 1000. The elements of the array are integers between -1000 and 1000.
Time limit 1 s (native code; slower languages get more)Memory 256 MB13 hidden tests
Example 1
Input
5 3 1 2 3 4 5
Output
6 9 12
Windows are [1,2,3], [2,3,4], [3,4,5]. Sums are 6, 9, 12.
Example 2
Input
4 4 10 20 30 40
Output
100
Only one window [10,20,30,40] with sum 100.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
5 3 1 2 3 4 5
Example 2 input
4 4 10 20 30 40