好吧,虽然这可能是一项任务,但我希望您能以一种通用且简洁的 STL 风格来做这些事情。
template<typename Iter, typename T = typename std::iterator_traits<Iter>::value_type>
std::pair<T, T> KConsecutiveMinMax(Iter first, Iter last, std::size_t K){
if(std::distance(first, last) < K) return {};
auto Sum = std::accumulate(first, first+K, T());
auto Min = Sum;
auto Max = Sum;
for(auto left = first, right = first + K; right != last; Sum -= *left++, Sum += *right++)
std::tie(Min, Max) = std::minmax(std::min(Min, Sum), std::max(Max, Sum));
return {Min, Max};
}
它添加数组的第一个 K 元素,将它们分配给 Sum、Max 和 Min,然后添加 K+1th 元素同时减去尾部元素。对于其中的每一个,它都会提取新的局部子序列之和的新Min 和Max
例子:
int main(){
std::vector<int> v{2, 39, 1, 9, 8, 6, 3, 10, -42, 3, 8, 3, 2};
auto ans = KConsecutiveMinMax(v.begin(), v.end(), 3);
std::cout << "Min = " << ans.first << ", and Max = " << ans.second << std::endl;
}
输出:
Min = -31, and Max = 49
Demo