股票最大利润 I


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


  • Best Time To Buy and Sell Stock
    Say you have an array for which the i th element is the price of a given stock on day i.
    If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

  • 题目大意:给定一个数组,第i个元素代表第i天股票的价格,只限一次买入和卖出,求最大收益。

  • 思路:找最低的价格,和它之后的最高价格,求差,再和已有的最大利润比较。不同于股票最大利润 II。在这个问题中,按那种思路找到的只是局部最大利润。

  • 代码:

#include
#include
using namespace std;
int maxProfit(vector &prices)
{
    // 价格数要大于等于两个才能考虑(重要)
    if(prices.size() < 2)return 0;
    int max_profit = 0;
    int min_price = prices.front();
    vector::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 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
欢迎来踩~~~~


你可能感兴趣的:(股票最大利润 I)