#K73712. Counting Valid Subarrays
Counting Valid Subarrays
Counting Valid Subarrays
You are given an integer array nums
and two integers m
and threshold
. Your task is to count the number of contiguous subarrays of length exactly m
whose sum is less than or equal to threshold
. Each subarray is defined by a consecutive segment of the array.
For example, consider the array [1, 2, 1, 1, 2, 1]
with m = 2
and threshold = 3
. The contiguous subarrays of length 2 are:
- [1, 2] with a sum of 3
- [2, 1] with a sum of 3
- [1, 1] with a sum of 2
- [1, 2] with a sum of 3
- [2, 1] with a sum of 3
All these 5 subarrays have sums less than or equal to the threshold. Your program should output the count of such subarrays.
Note: The formula for the sum of a subarray starting at index i (using 0-indexing) is given by:
You need to count all subarrays where \(S \leq threshold\).
inputFormat
The input is given from standard input (stdin) and consists of three parts:
- An integer
n
representing the number of elements in the array. - A line containing
n
space-separated integers representing the arraynums
. - A line containing two space-separated integers:
m
(the length of the subarray) andthreshold
.
If n
is zero, then the array is empty.
outputFormat
Output a single integer to standard output (stdout) representing the number of contiguous subarrays of length m
whose sum is less than or equal to threshold
.
5
4 5 6 1 2
2 6
1