首页 > 其他 > 详细

[leetcode]Best Time to Buy and Sell Stock

时间:2015-04-08 18:14:16      阅读:117      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!