Take an array of integers and an integer K. For all contiguous subarrays of length at least K, return the maximum average value (sum of all elements in the subarray divided by length of subarray, rounded down).
You may write a full program or a function. Input is the array and K, in any reasonable form and order. The length of the array will always be at least K. The array may contain negative integers, and negative values round down (2.9
to 2
, -2.1
to -3
).
Sample test (length of array, K, then array):
5 2
7 1 6 2 8
Output:
5
The optimal range here is taking [2, 8]. (2 + 8) / 2 = 5. An answer of 8 is not possible, because the subarray [8] has length 1, and the minimum length is 2.
[6, 2, 8] is another optimal range, with value (6 + 2 + 8) / 3 = 5.333, rounded down to 5.
This is code-golf, so shortest code wins! (In bytes.)
Test cases for validation:
K | Array | Output |
---|---|---|
3 | [7, 1, 6, 2, 8] |
5 |
2 | [7, 1, 7] |
5 |
1 | [1, 5, 7, 2, 9, 10] |
10 |
3 | [-2, -6, -8, -1, -17] |
-5 |
5 | [1, 2, 3, 4, 5] |
3 |
5
, since it asks for lengths of at least \$K\$. So the list is[7,1,7]
with average5.0
(sum15
and length3
), 'rounded down' to5
. \$\endgroup\$5
is the intended output.) \$\endgroup\$2.9
should be rounded down to2
and-2.1
to-3
? More test cases would be welcome. \$\endgroup\$