Index

Free, with Google

Keep going, free.

A free account opens lessons 2 and 3 of every track, 33 more lessons, and keeps your progress and review cards on every device.

Start free with Google

A chalk plan

Open everything on chalk.

Every lesson, board, video, lab and paper, and the full review decks. Yearly is $39/year.

See plansStart free instead

Maximum Average Subarray I

EasyLeetCode 643 ↗

The problem, in one line. Given a list of numbers and a width k, find the unbroken run of exactly k numbers with the highest average and return that average. LeetCode 643.

The tell. An unbroken run of a fixed width, scored by something you can update cheaply. When every run has the same width, the biggest average is simply the biggest sum, so you only need to compare sums.

The wrong first idea

Start at every position, add up the next k numbers, and keep the best.

best = float("-inf")
for i in range(len(nums) - k + 1):
    best = max(best, sum(nums[i:i + k]) / k)

Correct, and fine on a small list. It re-adds numbers it has already added. Two neighbouring runs share k minus 1 numbers, yet each one starts its sum from nothing. With 100,000 numbers and k of 50,000 that is about 2.5 billion additions.

The invariant

Add the first k numbers once. After that, sliding one step right means exactly one number enters on the right and one number leaves on the left. The new sum is the old sum plus the first minus the second.

[1, 12, -5, -6] 50, 3      sum 2
 1 [12, -5, -6, 50] 3      sum 2 + 50 - 1  = 51
 1, 12 [-5, -6, 50, 3]     sum 51 + 3 - 12 = 42

The sentence that stays true every step: window is the sum of exactly the k numbers ending at i. Two edits per step keep it true, so no step ever re-adds the middle.

The solution

def find_max_average(nums, k):
    window = sum(nums[:k])
    best = window                      # start from a real window, not from 0
    for i in range(k, len(nums)):
        window += nums[i] - nums[i - k]    # one number in, one number out
        best = max(best, window)
    return best / k

print(find_max_average([1, 12, -5, -6, 50, 3], 4))
print(find_max_average([5], 1))
print(find_max_average([-1, -2, -3], 2))
12.75
5.0
-1.5
func findMaxAverage(nums []int, k int) float64 {
	window := 0
	for _, x := range nums[:k] {
		window += x
	}
	best := window // start from a real window, not from 0
	for i := k; i < len(nums); i++ {
		window += nums[i] - nums[i-k] // one number in, one number out
		if window > best {
			best = window
		}
	}
	return float64(best) / float64(k)
}

Same three calls print 12.75, 5, -1.5. Go drops the .0 on a whole float.

Complexity

  • Time O(n): the first sum costs k, then each step does one add and one subtract.
  • Space O(1): two numbers, whatever the list size.

Traps

  • Starting best at 0. On [-1, -2, -3] with k of 2 it returns 0.0, an average no run has.
  • Stopping the loop one early. On [1, 1, 9] with k of 2 the last run [1, 9] is skipped and the answer is 1.0 instead of 5.0.
  • Dividing integers in Go. Write best / k on two ints and [1, 2] with k of 2 gives 1, not 1.5.

Next in the ladder

Best Time to Buy and Sell Stock keeps the same left and right pair but the window no longer has a fixed width: the left end jumps to wherever a better start appears.