Show problems as
Classic problem #643EasyArraySliding Window

Maximum Average Subarray I

Real-world version: Warmest Run of Days
Tracked in this browser only
Read Maximum Average Subarray I on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstRange Search · Binary Search, animated step by step

A weather station keeps one figure per day for a site: the daily anomaly, how far that day sat above or below the long-run norm, measured in tenths of a degree. A cold day carries a negative figure.

You are given the array anomalies, one figure per day in date order, and an integer span. Look at every block of span days that run back to back, work out the mean anomaly of each block as the block total divided by span, and report the largest mean any block reaches.

Return the mean as a real number; a reported figure off by less than 1e-5 from the true one is accepted. Since span never exceeds the number of days on record, at least one block always exists.

Examples

Example 1

Input
anomalies = [-3, 14, 2, -8, 21, 6], span = 3
Output
6.333333333333333

The four blocks total 13, 8, 15 and 19. The last three days total 19, the largest of them, so the mean reported is 19 divided by 3.

Example 2

Input
anomalies = [-9, -4], span = 2
Output
-6.5

Only one block of two days exists and both days ran cold, so the reported mean is negative.

Example 3

Input
anomalies = [7], span = 1
Output
7.0

A single day forms the only block, and a block of one day has that day's figure as its mean.

Constraints

  • n == anomalies.length
  • 1 <= span <= n <= 10^5
  • -10^4 <= anomalies[i] <= 10^4

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def warmest_run_average(anomalies: list[int], span: int) -> float:
Java
public double warmestRunAverage(int[] anomalies, int span)