THINK FIRST·CODE LATER

← All labs

Sliding-window maximum with a deque

Problem

Given n values and a window size k, print the maximum of every window of k consecutive values — in O(n) total, not O(n·k).

Write WindowMax using an ArrayDeque<Integer> of indexes whose values are kept in decreasing order: before adding index i, remove from the back every index whose value is ≤ a[i]; remove the front when it has left the window; the front is then the maximum. Count every deque operation (each add and each removal).

For the input

8 3
1 3 -1 -3 5 3 6 7

the program prints

Window maximums: 3 3 5 5 6 7
Deque operations: 15 (at most 2n = 16)
A nested loop would compare 18 values

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d4-4-data-1.txt

8 3
1 3 -1 -3 5 3 6 7
What your program must print for d4-4-data-1.txt
Window maximums: 3 3 5 5 6 7
Deque operations: 15 (at most 2n = 16)
A nested loop would compare 18 values

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d4-4-data-1.txt

Windows PowerShell does not understand <:

Get-Content d4-4-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.