<AI/>
enru
All posts

Maximum average subarray I

LeetCode 643: Find the contiguous subarray of length k with the maximum average value using a sliding window.

Difficulty
Easy
Published
Topics
#array#sliding window
Open on LeetCode

Problem Description

You are given an integer array nums of n elements and an integer k. Find a contiguous subarray of length k with the maximum average value and return that value.

Any answer with a calculation error less than 10-5 is accepted.

Constraints

  • k is guaranteed to be less than or equal to the length of nums
  • The number of elements is in the range from 1 to 105
  • Each element is in the range from -104 to 104

Examples

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

Answer: 12.75

Solution

We'll use the sliding window technique.

First, we compute the sum of the first k elements, effectively pre-filling a sliding window of length k. Then we create a variable maxSum that holds the maximum subarray sum and initialize it with the sum of the first k elements.

Next, we iterate over the array starting from element k up to the end. On each iteration we subtract from the window sum the element leaving the window on the left and add the element entering it on the right. Then we compare the current window sum with the maximum and update maxSum if the current one is greater.

After all iterations, maxSum holds the maximum sum of a subarray of length k. Finally, we divide this sum by k to get the average value of the subarray.

typescript
export const findMaxAverage = (nums: number[], k: number): number => {
  let sum = 0;
 
  for (let i = 0; i < k; i++) {
    sum += nums[i];
  }
 
  let maxSum = sum;
 
  for (let i = k; i < nums.length; i++) {
    sum = sum + nums[i] - nums[i - k];
    if (sum > maxSum) {
      maxSum = sum;
    }
  }
 
  return maxSum / k;
};

Complexity Analysis

Time Complexity

O(n), since we iterate over all elements of the array.

Space Complexity

O(1), since we don't allocate memory that depends on the array length.