zoukankan      html  css  js  c++  java
  • 数组同时求极值

    题目:假设你有一个数组,其中的第 i 个元素代表给定的第 i 天的股票价格。

    如果你被允许至多完成一个交易(如,买一和卖一股票),设计一个算法找出最大的利润。

    解决思路:首先赋首元素的值给最小,依次向后计算利润,每次与最大值比较并保存新的最大值和新的最小值。

    int MaxProfit (vector< int> prices)
    {
        int *min = &prices[0];
        int *max = min;
        auto len = prices.size ();
        for (decltype(len) i = 1; i < prices.size (); ++i) {
            if (prices[i] > *max)
                max = &prices[i];
            if (prices[i] <* min)
                min = &prices[i];
        }
        return *max  - *min;
    }

    int main ()
    {
        vector< int&gtprices;
        for (int i = 100; i > 0; --i)
            prices.push_back (i);
        cout << "The max profit is: " << MaxProfit(prices) << endl;
        return 0;
    }

  • 相关阅读:
    ZJOI2019爆蛋记
    NOIp2018退役记
    拓展中国剩余定理(exCRT)摘要
    FFT(快速傅里叶变换)摘要
    主席树摘要
    LCT摘要
    替罪羊树摘要
    FHQ Treap摘要
    逻辑回归1-逻辑回归原理详解
    NLP自然语言处理原理及名词介绍
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4098738.html
Copyright © 2011-2022 走看看