数组同时求极值

题目:假设你有一个数组,其中的第 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;
}

原文地址:https://www.cnblogs.com/wuOverflow/p/4098738.html