algorythms
Sliding Window
LC #643Easy

Maximum Average Subarray I

Sliding Window
AmazonGoogle

Problem

Given an integer array nums and integer k, find a contiguous subarray of exactly length k that has the maximum average value, and return that value. Example: nums=[1,12,-5,-6,50,3], k=4 → 12.75 (the subarray [12,-5,-6,50] has average 51/4 = 12.75).

arraysliding-window

Constraints

  • 1 ≤ k ≤ n ≤ 10⁵
  • -10⁴ ≤ nums[i] ≤ 10⁴

Example

Inputnums = [1, 12, -5, -6, 50, 3], k = 4
Output12.75
Why

[12, -5, -6, 50] → sum = 51, avg = 51/4 = 12.75

Hints — reveal one at a time