Drill

ProblemsTypeScript › patterns

How often the load crossed the line

mediumpatternsSliding windowArraysTypeScript

Capacity planning counts how many fixed-length stretches of the day carried at least a given amount of work.

windowsOverLimit(load: list<int>, runLength: int, limit: int) → int

Solve it in the editor →

Where you start

function windowsOverLimit(load: number[], runLength: number, limit: number): number {
  
}

Worked examples

CallResult
windowsOverLimit([1,2,3,4,5], 2, 5)3
windowsOverLimit([1,1,1], 2, 10)0
windowsOverLimit([5,5,5], 1, 5)3
windowsOverLimit([1,2], 3, 1)0

Hint

Slide one total across the list rather than re-summing each window, and test it at every stop.

Reference solution in TypeScript
function windowsOverLimit(load: number[], runLength: number, limit: number): number {
  if (runLength <= 0 || load.length < runLength) return 0;
  let window = 0;
  for (let i = 0; i < runLength; i += 1) window += load[i];
  let hits = window >= limit ? 1 : 0;
  for (let i = runLength; i < load.length; i += 1) {
    window += load[i] - load[i - runLength];
    if (window >= limit) hits += 1;
  }
  return hits;
}

The same problem in another language

More patterns problems in TypeScript