Find the biggest sum of 3 numbers in a row by sliding a window along: add the new number, drop the old one.
Python · intermediate · 6 min · 16 steps · free
def max_window_sum(nums, k):
window = sum(nums[:k])
best = window
for i in range(k, len(nums)):
window += nums[i] - nums[i - k]
best = max(best, window)
return best
print(max_window_sum([2, 1, 5, 1, 3, 2], 3))max_window_sum(). Its body does not run yet: it runs each time the function is called.max_window_sum(), with nums = [2, 1, 5, 1, 3, 2] and k = 3. It gets its own names.best is created with the value 8.i is created with the value 3.best = max(best, window).i changes from 3 to 4.window changes from 7 to 9.i changes from 4 to 5.window changes from 9 to 6.best = max(best, window).for i in range(k, len(nums)).best.max_window_sum() has finished, so its names are gone. It prints 9.Answer: O(1)
Answer: Yes
← Two Pointers · Bubble Sort →