Asked at

Maximum Average Subarray

Easy
Verified
ArraySliding Window~15 min

Given an array nums and an integer k, find the contiguous subarray of length k with the maximum average and return that average as a float.

Slide a fixed-size window of length k across the array, tracking the running sum, and keep the largest. The input arrives as a single object { nums, k }.

Examples

in{ nums: [1, 12, -5, -6, 50, 3], k: 4 }
out12.75

The window [12, -5, -6, 50] has the largest sum, 51, so average 51/4.

in{ nums: [5], k: 1 }
out5

Only one window exists.

Constraints

  • 1 ≤ k ≤ nums.length ≤ 10⁵
  • -10⁴ ≤ nums[i] ≤ 10⁴
  • Answers within 1e-5 of the true value are accepted.

Get help

🔑

Sign in to solve

Sign in to write, run, and submit your solution — and to pick up where your iOS flow left off.