TypeScript Flags
function flags(a: number[]): number {
const size = a.length;
const peaks: boolean[] = [false];
const next: number[] = [];
for (let i = 1; i < size; i++) {
peaks[i] = a[i - 1] < a[i] && a[i] > (a[i + 1] ?? 0);
}
next[size - 1] = -1;
for (let i = size - 2; i >= 0; i--) {
next[i] = peaks[i] ? i : next[i + 1];
}
let i = 1;
let result = 0;
while (i * (i - 1) <= size) {
let pos = 0;
let num = 0;
while (pos < size && num < i) {
pos = next[pos];
if (pos === -1) {
break;
}
++num;
pos += i;
}
i++;
result = Math.max(result, num);
}
return result;
}
This finds all peaks first, then checks how many flags can be placed while keeping the required distance.