You could check if the preceding calculated max value coincide with the first value of the preceding range: if not, the new max become the std::max
between the old max and the last position of the new interval.
Something as (caution: code not tested)
void f(const std::vector<double> &v, std::vector<double> &vv, size_t period)
{
vv.resize(v.size());
bool oldMaxFirst = false;
for (size_t i = period; i <= v.size(); ++i) {
if ( oldMaxFirst )
vv[i - 1] = std::max(vv[i - 2], v[i - 1]);
else
vv[i - 1] = *std::max_element(v.begin() + i - period, v.begin() + i);
oldMaxFirst = vv[i - 1] == v[i - period];
}
}
or also (but the code become a little obfuscated)
void f(const std::vector<double> &v, std::vector<double> &vv, size_t period)
{
vv.resize(v.size());
bool oldMaxFirst = false;
for (size_t i = period; i <= v.size(); ++i) {
oldMaxFirst = v[i - period] == (vv[i - 1] = (oldMaxFirst
? std::max(vv[i - 2], v[i - 1])
: *std::max_element(v.begin() + i - period, v.begin() + i) ); }
}