Problems › JavaScript › data
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>
Where you start
function windowMax(values, window) {
}
Worked examples
| Call | Result |
|---|---|
windowMax([1,3,2,5], 2) | [3,3,5] |
windowMax([1,2,3], 3) | [3] |
windowMax([5], 1) | [5] |
windowMax([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 JavaScript
function windowMax(values, window) {
if (window <= 0 || window > values.length) return [];
const result = [];
for (let i = 0; i + window <= values.length; i++) {
let m = values[i];
for (let j = i + 1; j < i + window; j++) if (values[j] > m) m = values[j];
result.push(m);
}
return result;
}