Loading practice problems…
Loading your practice workspace…
Loading code editor…
7 / 29
Sign in
Algorithms/Sliding Window

Maximum Average Subarray I

easy20 min

Given an integer array nums and an integer k, find the contiguous subarray of exactly k elements with the greatest average.

Return that maximum average.

Example 1

Inputnums = [1, 12, -5, -6, 50, 3], k = 4

Output12.75

The four consecutive values [12, -5, -6, 50] have the largest sum, 51. Their average is 51 ÷ 4 = 12.75.

Example 2

Inputnums = [5], k = 1

Output5

The only window contains 5, so its average is 5 ÷ 1 = 5.

Constraints

  • 1 ≤ k ≤ nums.length ≤ 100,000
  • -10,000 ≤ nums[i] ≤ 10,000
Sliding WindowArrays