首页 > 其他 > 详细

【Leetcode】121. Best Time to Buy and Sell Stock

时间:2018-04-22 20:48:41      阅读:172      评论:0      收藏:0      [点我收藏+]

题目地址:

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;
    }
};

 

【Leetcode】121. Best Time to Buy and Sell Stock

原文:https://www.cnblogs.com/AndrewGhost/p/8909088.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!