Leetcode121. Best Time to Buy and Sell Stock

Posted 业精于勤荒于嬉,行成于思毁于随

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode121. Best Time to Buy and Sell Stock相关的知识,希望对你有一定的参考价值。

题目地址:

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/

题目描述:

...

解决方案:

当前值减之前的数中的最小值得当前值最大利润,再更新最大利润即可

代码:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if (prices.size() < 2) {
            return 0;
        }
        int minPrice = prices.at(0);
        int maxProfit = 0;
        for (size_t i = 1; i < prices.size(); i++)
        {
            if (minPrice > prices.at(i)) {
                minPrice = prices.at(i);
                continue;
            }

            int profit = prices.at(i) - minPrice;
            if (profit > 0 && profit > maxProfit) {
                maxProfit = profit;
            }        
        }

        return maxProfit;
    }
};

 

以上是关于Leetcode121. Best Time to Buy and Sell Stock的主要内容,如果未能解决你的问题,请参考以下文章