首页 > 其他 > 详细

【leetcode】121-Best Time to Buy and Sell Stock

时间:2018-12-01 19:44:32      阅读:160      评论:0      收藏:0      [点我收藏+]

problem

121. Best Time to Buy and Sell Stock

code

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0;
        for(int i=0; i<prices.size(); i++)
        {
            int buy_price = prices[i];
            for(int j=i+1; j<prices.size(); j++)
            {
                int sell_price = prices[j];
                int tmp = sell_price - buy_price;
                if(tmp>res) res = tmp;
            }         
        }
        return res;
        
    }
};

one pass

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int min_price = INT_MAX;
        int max_profit = 0;
        for(int i=0; i<prices.size(); i++)
        {
            if(min_price> prices[i]) min_price = prices[i];
            else if(prices[i]-min_price>max_profit) max_profit = prices[i]-min_price;
        }
        return max_profit;
    }
};

 

参考

1. Leetcode_Best Time to Buy and Sell Stock;

【leetcode】121-Best Time to Buy and Sell Stock

原文:https://www.cnblogs.com/happyamyhope/p/10050580.html

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