98. Maximum of every window
A window of k items slides along a list one place at a time: first it covers items 0 to k - 1, then 1 to k,
and so on, until it reaches the end.
Write a function window_maxes(numbers, k) that returns the largest number in each position of the window, in order.
A list of n items has n - k + 1 windows.
- Numbers can repeat and can be negative.
kis at least 1 and at most the length of the list.
Taking max() of every window costs k steps each, n * k in all. There is a way that costs O(n) in all: keep the
indexes of the items that could still become a window's maximum, in a deque, their values falling from front to
back.
Example 1
numbers = [4, 2, 12, 3, 8, 1, 5], k = 3[12, 12, 12, 8, 8]Example 2
numbers = [9, 8, 7, 6], k = 2[9, 8, 7]Example 3
numbers = [5], k = 1[5]Constraints
numbershas 1 to 500 whole numbers, each from -10^4 to 10^4.kis from 1 tolen(numbers).
Submit also runs 8 more tests you can't see.
Practises Modules and Imports (lesson 22).
- Keep a
collections.dequeof indexes. An item that has a bigger (or equal) item after it in the window can never be a maximum again, so it needn't be kept. - For each new index
i: pop from the back every index whose value is<=the new value, then appendi. The values in the deque now fall from front to back. - If the front index has left the window (
q[0] <= i - k), pop it from the front. Oncei >= k - 1, the window is full and its maximum isnumbers[q[0]].
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def window_maxes(numbers, k):
"""Find the maximum of each window of k items.
numbers: list of int, at least one
k: int, from 1 to len(numbers)
Returns: list of int, the maximum of each window, from
the leftmost window to the rightmost
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.