oneby7

Sliding Window Fixed-size window

180. Maximum Average Subarray I

Easy

You are given an array of integers nums and an integer k. Look at every subarray of exactly k elements, and return the largest average among them.

A subarray is a contiguous sequence of elements from nums. The average of k numbers is their sum divided by k, so it can have a fractional part.

The answer is a floating-point number, and different correct ways of computing it can round differently in the last digits. So an answer counts as right when it is within 10−6 of the expected answer, or, for an expected answer larger than 1 in absolute value, within 10−6 times that answer.

Example 1

Input: nums = [5, -3, 8, 2, -4, 9, 6], k = 4

Output: 3.75

Explanation: The four subarrays of length 4 add up to 12, 3, 15 and 13. The best one is [8,2,-4,9], and its average is 15 / 4 = 3.75.

Example 2

Input: nums = [-7, -2, -9, -4, -1], k = 2

Output: -2.5

Explanation: Every pair of neighbours has a negative sum. The pair [-4,-1] loses the least, and its average is −5 / 2 = −2.5.

Example 3

Input: nums = [7, 0, -2, 4, 1, 0, 3, 1], k = 8

Output: 1.75

Explanation: Here k is the length of the array, so the only subarray is the whole array. Its sum is 14, and 14 / 8 = 1.75.

Check your understanding

Work out the answer for this input before you write any code.

nums = [2, 9, -10, 9, 2], k = 2

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • 1 ≤ k ≤ nums.length

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.