【问题标题】:the maximum of the mininums of all the k subsequences所有 k 个子序列的最小值中的最大值
【发布时间】:2017-08-15 23:00:25
【问题描述】:

你有一个由 n 个元素组成的序列。求取自 k 个元素的连续子序列的所有最小值中的最大值。 我尝试了采用所有长度为 k 的序列的经典方法。然后取最小值。并找到新的最小值数组中的最大值。

一个更优化的解决方案是找到前 k 个元素的最小值,然后在它之后跳转。你跳过了一些迭代。

你能给我一个更好更优化的解决方案吗? 没关系,但我使用的是 C++。

【问题讨论】:

  • 是excersize 吗?一个节目内容?

标签: c++ arrays minimum


【解决方案1】:

好吧,虽然这可能是一项任务,但我希望您能以一种通用且简洁的 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 元素,将它们分配给 SumMaxMin,然后添加 K+1th 元素同时减去尾部元素。对于其中的每一个,它都会提取新的局部子序列之和的新MinMax

例子:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-20
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多