Python 0643.py
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
total = sum(nums[:k-1])
result = float("-inf")
for i in range(k-1, len(nums)):
total += nums[i]
result = max(result, total / k)
total -= nums[i - k + 1]
return result
Difficulty
and has an acceptance rate of about 49% (2+ million submissions).
Typical patterns to solve this problem:
- Array
- Sliding Window
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the maximum average of any contiguous sub-array of length k within the input list nums. It employs a sliding-window technique that maintains the sum of the current window while iterating once through the array. By updating the sum incrementally, the algorithm avoids recomputing the total for each possible sub-array, achieving linear traversal.
Initialization
The algorithm begins by preparing two variables:
total = sum(nums[:k-1])
result = float("-inf")
total holds the sum of the first k-1 elements, establishing the baseline for the first full window that will be formed when the loop reaches index k-1.
result is seeded with negative infinity so that any legitimate average encountered will replace it, even when all numbers are negative.
Sliding-Window Loop
The core of the solution is a single for loop that expands the window to size k, evaluates the average, and then contracts the window from the left:
for i in range(k-1, len(nums)):
total += nums[i] # extend window to include nums[i]
result = max(result, total / k) # compute average of current window
total -= nums[i - k + 1] # remove leftmost element of window
- The statement
total += nums[i]adds the new rightmost element, completing a window of exactlykelements. result = max(result, total / k)calculates the average of the current window and retains the greatest value seen so far.total -= nums[i - k + 1]subtracts the element that falls out of the window as the left boundary moves forward, preparingtotalfor the next iteration.
Edge-Case Handling
The code gracefully addresses several boundary conditions without additional checks:
- Window size equal to the array length - When
kequalslen(nums), the loop runs exactly once, producing the average of the entire array. - Window size of one - With
k == 1, the initialtotalis the sum of an empty slice (0). Each iteration adds a single element, computes its average (the element itself), and then removes it, effectively scanning every element individually. - All negative numbers - Starting
resultat negative infinity ensures that the maximum average among negative values is still captured. - Identical elements - The sliding window will repeatedly compute the same average; the
maxoperation simply retains that value. - Empty slice handling - Python’s
sum([])returns0, so the initialization works even whenkis1.
Performance Optimizations
The implementation incorporates several deliberate choices that keep execution efficient:
- Incremental sum update - By adding the incoming element and subtracting the outgoing element, the algorithm maintains the window sum in constant time per iteration, eliminating the need for an inner loop or repeated
sumcalls. - Single pass over the data - The
forloop traverses the list exactly once, guaranteeing linear time proportional to the length ofnums. - Minimal auxiliary storage - Only two scalar variables (
totalandresult) are used regardless of input size, resulting in constant extra memory consumption. - Use of built-in
max- Leveraging Python’s optimizedmaxfunction for a two-argument comparison avoids manual conditional branching. - Floating-point division only when needed - The division
total / koccurs once per window, and the divisorkis a constant, allowing the interpreter to reuse the division operation efficiently.
Overall, the code delivers a concise and performant solution for finding the maximum average sub-array of fixed length.
ELI5 - Simplified Explanation
Imagine a long toy train made of many different colored cars. Each car has a number painted on the side. This code is like a little robot helper that wants to find the best group of cars to look at. The robot starts by grabbing a small group of cars, specifically the number of cars told to it, and adds all their numbers together to see the total.
The robot then moves down the line of cars one by one. Each time it slides over, it adds the very next car to its group and takes away the one from the back that is no longer in the group. This helps the robot keep the same size group as it moves across the whole train. Because the robot wants to find the biggest average, it checks the sum of its group every time it slides. It keeps a mental note of the highest number it has seen so far. Once the robot reaches the very end of the line, it stops moving.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||||
| WalkCCC | C++ | Python | Java | |||||||||
| leetcode.ca | C++ | Python | Java | Go | Rust | PHP | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | BigEggStudy | C# | ||||||||||
| black-shadows | C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| halfrost | Go | |||||||||||
| haoel | Python | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| linouk23 | Python | |||||||||||
| lkwq007 | Python | |||||||||||
| lzl124631x | C++ | |||||||||||
| muhammadfarhankt | Go | |||||||||||
| ruoru | Rust | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, PHP, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| halfrost | Go | |||||||||||
| haoel | Python | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| linouk23 | Python | |||||||||||
| lkwq007 | Python | |||||||||||
| lzl124631x | C++ | |||||||||||
| muhammadfarhankt | Go | |||||||||||
| ruoru | Rust | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 644: Maximum Average Subarray II
- problem 2090: K Radius Subarray Averages
Solved On The Same Day
- problem 1431: Kids With the Greatest Number of Candies
- problem 310: Minimum Height Trees
- problem 334: Increasing Triplet Subsequence
- problem 355: Design Twitter
- problem 368: Largest Divisible Subset
- problem 382: Linked List Random Node
- problem 398: Random Pick Index
- problem 1004: Max Consecutive Ones III
- problem 1318: Minimum Flips to Make a OR b Equal to c
- problem 1679: Max Number of K-Sum Pairs
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality