股票最大利润 I

2018-12-04  本文已影响0人  静水流深ylyang

版权声明:本文为博主原创文章,转载请注明出处。
个人博客地址:https://yangyuanlin.club
欢迎来踩~~~~


#include<iostream>
#include<vector>
using namespace std;
int maxProfit(vector<int> &prices)
{
    // 价格数要大于等于两个才能考虑(重要)
    if(prices.size() < 2)return 0;
    int max_profit = 0;
    int min_price = prices.front();
    vector<int>::iterator it;
    for(it = prices.begin()+1; it != prices.end(); it++)
    {
        // 比较寻找最低利润
        min_price = min_price < *it ? min_price : *it;
        // 跟当前已找到的最高利润作比较
        max_profit = max_profit > (*it - min_price) ? max_profit : (*it - min_price);
    }
    return max_profit > 0 ? max_profit : 0;
}
int main()
{
    vector<int> prices;
    for(int i = 0; i < 10; i++)
    {
        int a;
        cin >> a;
        prices.push_back(a);
    }
    cout << maxProfit(prices) << endl;
    return 0;
}

版权声明:本文为博主原创文章,转载请注明出处。
个人博客地址:https://yangyuanlin.club
欢迎来踩~~~~


上一篇 下一篇

猜你喜欢

热点阅读