โ† Amazon questions

Max average subarray

Filed under Amazon

Free read 1 of 3

The maximum possible average of any subarray is equal to max(nums). Subarrays achieving this average must consist exclusively of max(nums).

The question

Given an array of integers nums, find the maximum length of a contiguous subarray that achieves the maximum possible average value among all contiguous non-empty subarrays.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4

Examples

Input
nums = [1, 3, 3, 2, 3, 3, 3]
Output
3
Why
The maximum average of any subarray is 3. The longest contiguous subarray with average 3 is [3, 3, 3] of length 3.
Input
nums = [2, 2, 2, 2]
Output
4
Why
The maximum average is 2, achieved by the full array of length 4.

Approach

  1. The maximum possible average of any subarray is equal to max(nums). Subarrays achieving this average must consist exclusively of max(nums).

Solution

O(N) time, O(1) space

Python
class Solution:
    def findLengthOfMaxAverageSubarray(self, nums: list[int]) -> int:
        if not nums:
            return 0
        max_val = max(nums)
        max_len = 0
        curr_len = 0
        for num in nums:
            if num == max_val:
                curr_len += 1
                max_len = max(max_len, curr_len)
            else:
                curr_len = 0
        return max_len

Tips

  • What they are testing: Tests mathematical insight into averages and the ability to simplify complex-sounding problems into linear scans.
  • Common mistake: Attempting dynamic programming or sliding window algorithms to compute subsegment sums instead of recognizing max average equals max single element.

Related Amazon questions

Collected from public candidate posts and coding forums. Updated Nov 2026.