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

[leetcode]Best Time to Buy and Sell Stock

时间:2015-04-08 18:16:49      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

Say you have an array for which the ith 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.

这一很直观,直接找差值最大就行了,一开始TLE一次,因为用了O(n^2)
的方法,后来发现O(n)就可以。
一开始的代码:

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

正确的:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.size()==0 || prices.size()==1) return 0;
        int ans = INT_MIN ;
        int low = prices[0];
        for(int i=1;i<prices.size();i++){
            if(low > prices[i]) low = prices[i];
            else if(prices[j] - low >ans) ans = prices[j] - low;
        }
        return ans;
    }
};

[leetcode]Best Time to Buy and Sell Stock

标签:

原文地址:http://blog.csdn.net/iboxty/article/details/44942595

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