码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-12-01 20:15:39      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:div   tmp   ble   solution   pull   esc   http   min   max   

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

标签:div   tmp   ble   solution   pull   esc   http   min   max   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!