Drill

ProblemsJavaScript › data

The peak in each window

harddataJavaScript

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

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

Solve it in the editor →

Where you start

function windowMax(values, window) {
  
}

Worked examples

CallResult
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;
}

The same problem in another language

More data problems in JavaScript