Maximum Average Subarray I

You are given an integer array `nums` of n elements and an integer `k`. Find a contiguous subarray of length exactly `k` that has the maximum average value and return that average. Answers within $10^{-5}$ of the true value are accepted.

30:00

Maximum Average Subarray I
easy
Free written solution
Topics
Companies

You are given an integer array nums of n elements and an integer k. Find a contiguous subarray of length exactly k that has the maximum average value and return that average. Answers within 10−510^{-5} of the true value are accepted.

Example 1:
Input: {"nums":[1,12,-5,-6,50,3],"k":4}
Output: 12.75
Constraints:
  • n==nums.lengthn == \text{nums.length}

  • 1≤k≤n≤1051 \leq k \leq n \leq 10^5

  • −104≤nums[i]≤104-10^4 \leq \text{nums}[i] \leq 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,12,-5,-6,50,3],"k":4}

The window has a fixed width of k = 4. Start by summing the first 4 numbers.

k (width)

4

window sum

0

best sum

0

best avg

0.0

building the first window: 0 of 4

1

0

12

1

-5

2

-6

3

50

4

3

5

window sum at each start

Variables
VariableValue
k4
window0
DepthFunction Call
Stack empty
0/10