Taro Logo

Maximum Average Subarray I

Easy
1 views
22 days ago

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^{-5} will be accepted.

Example 1:

Input: nums = [1,12,-5,-6,50,3], k = 4
Output: 12.75000
Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75

Example 2:

Input: nums = [5], k = 1
Output: 5.00000

Constraints:

  • n == nums.length
  • 1 <= k <= n <= 10^5
  • -10^4 <= nums[i] <= 10^4
Sample Answer
class Solution:
    def findMaxAverage(self, nums: list[int], k: int) -> float:
        """Finds the maximum average of a subarray of length k in the given array nums."""

        # Calculate the sum of the first k elements.
        current_sum = sum(nums[:k])
        max_sum = current_sum

        # Iterate through the rest of the array, updating the sum by subtracting the first element of the previous window and adding the next element.
        for i in range(k, len(nums)):
            current_sum += nums[i] - nums[i - k]
            max_sum = max(max_sum, current_sum)

        # Return the maximum average.
        return max_sum / k

# Example Usage:
# nums = [1,12,-5,-6,50,3]
# k = 4
# solution = Solution()
# result = solution.findMaxAverage(nums, k)
# print(result)

Functionality

The function findMaxAverage takes a list of integers nums and an integer k as input. It calculates the maximum average of all contiguous subarrays of length k in the input array nums. It uses a sliding window approach to efficiently compute the sum of each subarray of length k and keeps track of the maximum sum encountered.

Naive Solution

A naive solution would involve iterating through all possible subarrays of length k, calculating the sum of each subarray, and keeping track of the maximum sum. However, this approach has a time complexity of O(n*k), where n is the length of the input array, as it requires iterating through all possible starting positions for the subarray and then summing up the elements within each subarray.

class Solution:
    def findMaxAverage(self, nums: list[int], k: int) -> float:
        """Finds the maximum average of a subarray of length k in the given array nums (Naive Solution)."""
        n = len(nums)
        max_avg = float('-inf')

        for i in range(n - k + 1):
            current_sum = 0
            for j in range(k):
                current_sum += nums[i + j]
            max_avg = max(max_avg, current_sum / k)

        return max_avg

Optimal Solution

The provided solution utilizes a sliding window approach. It calculates the sum of the first k elements and then iterates through the rest of the array, updating the sum by subtracting the element that is no longer in the window and adding the next element. This approach has a time complexity of O(n), where n is the length of the input array, as it only requires iterating through the array once.

Big O Time Complexity Analysis

The time complexity of the optimal solution is O(n), where n is the length of the input array nums. This is because the code iterates through the array once to calculate the sum of each subarray of length k using the sliding window technique. The sum(nums[:k]) operation takes O(k) time initially, but it is performed only once. The loop iterates n - k times, and each iteration involves constant-time operations (addition, subtraction, and comparison). Therefore, the overall time complexity is dominated by the loop, resulting in O(n).

Big O Space Complexity Analysis

The space complexity of the optimal solution is O(1). The code uses a constant amount of extra space to store variables such as current_sum and max_sum, regardless of the size of the input array. Therefore, the space complexity is constant, denoted as O(1).

Edge Cases

  1. Empty Array: If the input array nums is empty, the code should handle this case gracefully by returning 0 or raising an exception, as it's not possible to find a subarray of length k in an empty array.
  2. Invalid k: If k is less than or equal to 0 or greater than the length of nums, the code should raise an exception or return an appropriate error value, as these are invalid inputs.
  3. Single Element Array: If nums contains only one element and k is 1, the code should return the value of that element as a float.
  4. Array with all Negative Numbers: The code should handle arrays with all negative numbers correctly, ensuring that it finds the maximum average among the negative subarrays.
  5. Large Input: For very large arrays, the code should be optimized to avoid potential integer overflow issues when calculating the sum of subarrays. Using floating-point numbers for intermediate sums can help prevent overflow.