スライディングウィンドウで最高の1秒を見つける
function peakRate(times, windowMs = 1000) { let peak = 0; let start = 0; for (let end = 0; end < times.length; end += 1) { while (times[end] - times[start] >= windowMs) start += 1; peak = Math.max(peak, end - start + 1); } return peak;}
// Press times in milliseconds since the first press.const times = [0, 900, 1800, 2700, 2800, 2900, 3000, 3100, 4500];console.log(peakRate(times)); // 5ウィンドウは押した瞬間で終わり、そこから1秒前までさかのぼります。そこから外れた分は先頭から外していき、見つかったいちばん大きいウィンドウが最高になります。この例では、2700ミリ秒から3100ミリ秒までの5回が同じ1秒に入っています。