DSA AnimatorREVISION VIDEOS
← Back to problems
New

Maximum Average Subarray I — LeetCode 643 video explanation

Given an array and a number k, find the contiguous subarray of length k with the largest average. Return that average.

Loading videos…

DSA Animator › DSA Revision › Arrays › Maximum Average Subarray I

Key moments in the Maximum Average Subarray I video

0:04Problem0:12Example0:25Brute force0:33Key idea0:46Dry run1:05Code1:21Takeaway

What you will learn

Remember: a fixed window slides by adding the new number and removing the oldest. Same length means the largest average is the largest sum. The video solves Maximum Average Subarray I (LeetCode 643, Easy) with the Fixed Sliding Window pattern from the Arrays topic, and you can replay every step in the interactive Maximum Average Subarray I animation.

Maximum Average Subarray I video transcript

Problem

Given an array and a number k, find the contiguous subarray of length k with the largest average. Return that average.

Example

For 1, 12, minus 5, minus 6, 50, 3, with k equal to 4, the best window is 12, minus 5, minus 6, 50. Its sum is 51, so the average is 12.75.

Brute force

Summing every window from scratch costs O of n times k. Neighbouring windows share almost all their numbers, so that work is repeated.

Key idea

Since every window has the same length, the largest average is just the largest sum. Compute the first window once. Then slide: add the number entering on the right, and subtract the one leaving on the left.

Dry run

The first window, 1, 12, minus 5, minus 6, sums to 2. Slide right: 50 comes in and 1 leaves, so the sum becomes 51, the new best. Slide again: 3 comes in and 12 leaves, so the sum drops to 42. The best sum is 51, and 51 divided by 4 is 12.75.

Code

In code, add up the first k numbers. Then for each new index, add the incoming number and subtract the one k places back. Keep the largest sum, and divide by k at the end. Each number is added and removed once, so it's O of n time and O of 1 space.

Takeaway

Remember: a fixed window slides by adding the new number and removing the oldest. Same length means the largest average is the largest sum.

More Arrays revision videos

← All 185 DSA revision videos