You are given an integer array nums consisting of n elements, and an integer k.
Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10⁻⁵ will be accepted.
windowSum += nums[i] - nums[i - k]. This keeps the sum update at O(1).return maxSum / k.Stock traders use moving averages to smooth price data and spot trends. A k-day moving average recomputes the average over the last k closing prices. The sliding window approach means you never resum all k prices — you just add today's price and drop the oldest, making it O(1) per update instead of O(k). This same pattern powers signal processing, weather forecasting, and real-time sensor analytics.
This is the textbook fixed-size sliding window problem. Build the initial window of size k once in O(k), then slide it right by updating the sum in O(1) per step.
windowSum = sum(nums[:k]). Set maxSum = windowSum.i from k to n-1: windowSum += nums[i] - nums[i-k].maxSum = max(maxSum, windowSum).maxSum / k.The key insight: when the window slides, the sum changes by exactly nums[i] - nums[i-k] — one addition, one subtraction. This gives O(n) total with O(1) space.
Discussion
…