C++ Flags
#include <algorithm>
#include <vector>
int flags(const std::vector<int>& a)
{
int size = static_cast<int>(a.size());
if (size == 0) {
return 0;
}
std::vector<bool> peaks(size, false);
for (int i = 1; i < size; ++i) {
int nextVal = (i + 1 < size) ? a[i + 1] : 0;
peaks[i] = a[i - 1] < a[i] && a[i] > nextVal;
}
std::vector<int> next(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 = std::max(result, num);
}
return result;
}
This finds all peaks first, then checks how many flags can be placed while keeping the required distance.