KatInterview

644. Maximum Average Subarray II

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the maximum average of a contiguous subarray with a length of at least k. A naive approach would be to iterate through all possible subarrays of length k or more, calculate their averages, and find the maximum. This would involve checking approximately O(n^2) subarrays, leading to a time complexity of O(n^2) if using prefix sums, which is too slow for n up to 10^4.

Solution

Maximum Average Subarray II in Python

class Solution:
    def findMaxAverage(self, nums: List[int], k: int) -> float:
        # Set the initial search range for the average.
        # The average must be between the min and max values of the array.
        l, r = float(min(nums)), float(max(nums))

        # Binary search for the maximum average.
        # We continue until the range [l, r] is smaller than the required precision.
        while r - l > 1e-5:
            mid = (l + r) / 2
            if self.check(nums, k, mid):
                # If an average of 'mid' is achievable, we try for a larger average.
                l = mid
            else:
                # If 'mid' is not achievable, we need to aim for a smaller average.
                r = mid
        return l

    # check(avg) returns true if there is a subarray of length >= k with an average >= avg.
    def check(self, nums: List[int], k: int, avg: float) -> bool:
        n = len(nums)
        # prefix_sum[i] stores the sum of (nums[j] - avg) for j from 0 to i-1.
        prefix_sum = [0.0] * (n + 1)
        for i in range(n):
            prefix_sum[i + 1] = prefix_sum[i] + (nums[i] - avg)

        # To find if there's a subarray nums[i..j] with length >= k and average >= avg,
        # we check if (nums[i]-avg) + ... + (nums[j]-avg) >= 0.
        # This is equivalent to prefix_sum[j+1] - prefix_sum[i] >= 0, or prefix_sum[j+1] >= prefix_sum[i].
        # For a fixed j, we want to find an i such that i <= j-k+1 and prefix_sum[i] is minimal.
        
        min_prev_sum = 0.0
        for i in range(k, n + 1):
            # We are looking for a subarray of length at least k ending at index i-1.
            # The start index of such a subarray can be at most i-k.
            # The sum of (num - avg) from start to i-1 is prefix_sum[i] - prefix_sum[start].
            # We want to maximize this, so we need to minimize prefix_sum[start].
            # min_prev_sum tracks the minimum prefix sum up to index i-k.
            min_prev_sum = min(min_prev_sum, prefix_sum[i - k])
            if prefix_sum[i] >= min_prev_sum:
                return True
        return False

Maximum Average Subarray II in Java

class Solution {
    public double findMaxAverage(int[] nums, int k) {
        double l = 10001, r = -10001;
        // Find the min and max values in nums to set a tighter search range for the average.
        for (int x : nums) {
            l = Math.min(l, x);
            r = Math.max(r, x);
        }

        // Binary search for the maximum average.
        // We continue until the range [l, r] is smaller than the required precision.
        while (r - l > 1e-5) {
            double mid = l + (r - l) / 2;
            if (check(nums, k, mid)) {
                // If an average of 'mid' is achievable, we try for a larger average.
                l = mid;
            } else {
                // If 'mid' is not achievable, we need to aim for a smaller average.
                r = mid;
            }
        }
        return l;
    }

    // check(avg) returns true if there is a subarray of length >= k with an average >= avg.
    private boolean check(int[] nums, int k, double avg) {
        int n = nums.length;
        // prefixSum[i] stores the sum of (nums[j] - avg) for j from 0 to i-1.
        double[] prefixSum = new double[n + 1];
        for (int i = 0; i < n; i++) {
            prefixSum[i + 1] = prefixSum[i] + (nums[i] - avg);
        }

        // To find if there's a subarray nums[i..j] with length >= k and average >= avg,
        // we check if (nums[i]-avg) + ... + (nums[j]-avg) >= 0.
        // This is equivalent to prefixSum[j+1] - prefixSum[i] >= 0, or prefixSum[j+1] >= prefixSum[i].
        // For a fixed j, we want to find an i such that i <= j-k+1 and prefixSum[i] is minimal.
        
        double minPrevSum = 0;
        for (int i = k; i <= n; i++) {
            // We are looking for a subarray of length at least k ending at index i-1.
            // The start index of such a subarray can be at most i-k.
            // The sum of (num - avg) from start to i-1 is prefixSum[i] - prefixSum[start].
            // We want to maximize this, so we need to minimize prefixSum[start].
            // minPrevSum tracks the minimum prefix sum up to index i-k.
            minPrevSum = Math.min(minPrevSum, prefixSum[i - k]);
            if (prefixSum[i] >= minPrevSum) {
                return true;
            }
        }
        return false;
    }
}

Maximum Average Subarray II in C++

class Solution {
public:
    double findMaxAverage(vector<int>& nums, int k) {
        double l = 1e5, r = -1e5;
        // Find the min and max values in nums to set a tighter search range for the average.
        for (int x : nums) {
            l = min(l, (double)x);
            r = max(r, (double)x);
        }

        // Binary search for the maximum average.
        // We continue until the range [l, r] is smaller than the required precision.
        while (r - l > 1e-5) {
            double mid = l + (r - l) / 2;
            if (check(nums, k, mid)) {
                // If an average of 'mid' is achievable, we try for a larger average.
                l = mid;
            } else {
                // If 'mid' is not achievable, we need to aim for a smaller average.
                r = mid;
            }
        }
        return l;
    }

private:
    // check(avg) returns true if there is a subarray of length >= k with an average >= avg.
    bool check(vector<int>& nums, int k, double avg) {
        int n = nums.size();
        // prefix_sum[i] stores the sum of (nums[j] - avg) for j from 0 to i-1.
        vector<double> prefix_sum(n + 1, 0.0);
        for (int i = 0; i < n; ++i) {
            prefix_sum[i + 1] = prefix_sum[i] + (nums[i] - avg);
        }

        // To find if there's a subarray nums[i..j] with length >= k and average >= avg,
        // we check if (nums[i]-avg) + ... + (nums[j]-avg) >= 0.
        // This is equivalent to prefix_sum[j+1] - prefix_sum[i] >= 0, or prefix_sum[j+1] >= prefix_sum[i].
        // For a fixed j, we want to find an i such that i <= j-k+1 and prefix_sum[i] is minimal.
        
        double min_prev_sum = 0;
        for (int i = k; i <= n; ++i) {
            // We are looking for a subarray of length at least k ending at index i-1.
            // The start index of such a subarray can be at most i-k.
            // The sum of (num - avg) from start to i-1 is prefix_sum[i] - prefix_sum[start].
            // We want to maximize this, so we need to minimize prefix_sum[start].
            // min_prev_sum tracks the minimum prefix_sum up to index i-k.
            min_prev_sum = min(min_prev_sum, prefix_sum[i - k]);
            if (prefix_sum[i] >= min_prev_sum) {
                return true;
            }
        }
        return false;
    }
};

Maximum Average Subarray II in TypeScript

function findMaxAverage(nums: number[], k: number): number {
    let l: number = 10001, r: number = -10001;
    // Find the min and max values in nums to set a tighter search range for the average.
    for (const x of nums) {
        l = Math.min(l, x);
        r = Math.max(r, x);
    }

    // Binary search for the maximum average.
    // We continue until the range [l, r] is smaller than the required precision.
    while (r - l > 1e-5) {
        const mid: number = l + (r - l) / 2;
        if (check(nums, k, mid)) {
            // If an average of 'mid' is achievable, we try for a larger average.
            l = mid;
        } else {
            // If 'mid' is not achievable, we need to aim for a smaller average.
            r = mid;
        }
    }
    return l;
}

// check(avg) returns true if there is a subarray of length >= k with an average >= avg.
function check(nums: number[], k: number, avg: number): boolean {
    const n = nums.length;
    // prefixSum[i] stores the sum of (nums[j] - avg) for j from 0 to i-1.
    const prefixSum: number[] = new Array(n + 1).fill(0);
    for (let i = 0; i < n; i++) {
        prefixSum[i + 1] = prefixSum[i] + (nums[i] - avg);
    }

    // To find if there's a subarray nums[i..j] with length >= k and average >= avg,
    // we check if (nums[i]-avg) + ... + (nums[j]-avg) >= 0.
    // This is equivalent to prefixSum[j+1] - prefixSum[i] >= 0, or prefixSum[j+1] >= prefixSum[i].
    // For a fixed j, we want to find an i such that i <= j-k+1 and prefixSum[i] is minimal.
    
    let minPrevSum: number = 0;
    for (let i = k; i <= n; i++) {
        // We are looking for a subarray of length at least k ending at index i-1.
        // The start index of such a subarray can be at most i-k.
        // The sum of (num - avg) from start to i-1 is prefixSum[i] - prefixSum[start].
        // We want to maximize this, so we need to minimize prefixSum[start].
        // minPrevSum tracks the minimum prefix sum up to index i-k.
        minPrevSum = Math.min(minPrevSum, prefixSum[i - k]);
        if (prefixSum[i] >= minPrevSum) {
            return true;
        }
    }
    return false;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.