Java Flags
public class Solution {
public static int flags(int[] a) {
int size = a.length;
boolean[] peaks = new boolean[size];
for (int i = 1; i < size; i++) {
int next = (i + 1 < size) ? a[i + 1] : 0;
peaks[i] = a[i - 1] < a[i] && a[i] > next;
}
int[] next = new int[size];
next[size - 1] = -1;
for (int i = size - 2; i >= 0; i--) {
next[i] = peaks[i] ? i : next[i + 1];
}
int i = 1;
int result = 0;
while (i * (i - 1) <= size) {
int pos = 0;
int 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.