Maximize the Average of an Exactly K-Length Segment

Quick Overview

Maximize the Average of an Exactly K-Length Segment. Return the greatest average among contiguous subarrays of nums containing exactly k elements.

Maximize the Average of an Exactly K-Length Segment

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

### Problem Return the greatest average among contiguous subarrays of nums containing exactly k elements. Answers with calculation error less than 10^-5 are accepted. ```cpp class Solution { public: double findMaxAverage(vector<int>& nums, int k); }; ``` ### Examples **Example 1:** ```text nums = [4,-2,6,8], k = 2 Output: 7.0 Explanation: The final pair has sum 14 and average 7. ``` **Example 2:** ```text nums = [-5,-1,-7], k = 1 Output: -1.0 Explanation: A one-element window selects the largest value. ``` ### Constraints - The n-element array and window satisfy `1 <= k <= n <= 100000`. Every value is in -10000..10000. ### Clarifying Questions Use exactly k elements, preserve negative averages and retain the source's acceptance tolerance. ```hint Read the boundary condition Can equal-length windows be compared using their sums alone? ``` ### Contract considerations Use exactly k elements, preserve negative averages and retain the source's acceptance tolerance.

Overview: Maximize the Average of an Exactly K-Length Segment. Return the greatest average among contiguous subarrays of nums containing exactly k elements.

Amazon logo
Amazon
Sep 11, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Problem

Return the greatest average among contiguous subarrays of nums containing exactly k elements. Answers with calculation error less than 10^-5 are accepted.

class Solution {
public:
    double findMaxAverage(vector<int>& nums, int k);
};

Examples

Example 1:

nums = [4,-2,6,8], k = 2
Output: 7.0
Explanation: The final pair has sum 14 and average 7.

Example 2:

nums = [-5,-1,-7], k = 1
Output: -1.0
Explanation: A one-element window selects the largest value.

Constraints

  • The n-element array and window satisfy 1 <= k <= n <= 100000 . Every value is in -10000..10000.

Clarifying Questions Guidance

Use exactly k elements, preserve negative averages and retain the source's acceptance tolerance.

Contract considerations

Use exactly k elements, preserve negative averages and retain the source's acceptance tolerance.