The peak in each window
A monitoring chart smooths readings by asking, for each fixed-size window, what the loudest moment inside it was.
- Each output entry is the largest value inside one contiguous window of size `window`.
- The windows slide by one position at a time.
- A window of zero or less, or one larger than the whole list, gives an empty result.
windowMax(values: list<int>, window: int) → list<int>
Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
List<Integer> windowMax(List<Integer> values, int window) {
}
Worked examples
| Call | Result |
|---|---|
windowMax(Main.<Integer>ls(1, 3, 2, 5), 2) | Main.<Integer>ls(3, 3, 5) |
windowMax(Main.<Integer>ls(1, 2, 3), 3) | Main.<Integer>ls(3) |
windowMax(Main.<Integer>ls(5), 1) | Main.<Integer>ls(5) |
windowMax(Main.<Integer>ls(4, 1, 3), 2) | Main.<Integer>ls(4, 3) |
Hint
For each starting index take the maximum of the next `window` values with an inner loop.
Reference solution in Java
List<Integer> windowMax(List<Integer> values, int window) {
List<Integer> result = new ArrayList<>();
if (window <= 0 || window > values.size()) return result;
for (int i = 0; i + window <= values.size(); i++) {
int m = values.get(i);
for (int j = i + 1; j < i + window; j++) if (values.get(j) > m) m = values.get(j);
result.add(m);
}
return result;
}