Problem 643

Abstract / Summary

Given an array of numbers and an integer length, find the maximum average of any contiguous subarray of that length.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
10 lines | 327 bytes | submitted September 11, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 49% (2+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Sliding Window
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 exactly k elements.
  • 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, preparing total for the next iteration.

Edge-Case Handling

The code gracefully addresses several boundary conditions without additional checks:

  • Window size equal to the array length - When k equals len(nums), the loop runs exactly once, producing the average of the entire array.
  • Window size of one - With k == 1, the initial total is 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 result at 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 max operation simply retains that value.
  • Empty slice handling - Python’s sum([]) returns 0, so the initialization works even when k is 1.

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 sum calls.
  • Single pass over the data - The for loop traverses the list exactly once, guaranteeing linear time proportional to the length of nums.
  • Minimal auxiliary storage - Only two scalar variables (total and result) are used regardless of input size, resulting in constant extra memory consumption.
  • Use of built-in max - Leveraging Python’s optimized max function for a two-argument comparison avoids manual conditional branching.
  • Floating-point division only when needed - The division total / k occurs once per window, and the divisor k is 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.15 | σ = 0.85

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
41 links | 26 authors | 11 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

11 solutions   September 11, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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