Drill

ProblemsPython › data

The peak in each window

harddataPython

A monitoring chart smooths readings by asking, for each fixed-size window, what the loudest moment inside it was.

window_max(values: list<int>, window: int) → list<int>

Solve it in the editor →

Where you start

def window_max(values: list[int], window: int) -> list[int]:
    

Worked examples

CallResult
window_max([1, 3, 2, 5], 2)[3, 3, 5]
window_max([1, 2, 3], 3)[3]
window_max([5], 1)[5]
window_max([4, 1, 3], 2)[4, 3]

Hint

For each starting index take the maximum of the next `window` values with an inner loop.

Reference solution in Python
def window_max(values: list[int], window: int) -> list[int]:
    result = []
    if window <= 0 or window > len(values):
        return result
    for i in range(len(values) - window + 1):
        m = values[i]
        for j in range(i + 1, i + window):
            if values[j] > m:
                m = values[j]
        result.append(m)
    return result

The same problem in another language

More data problems in Python