LeetCode:Best Time to Buy and Sell Stock

Title:Best Time to Buy and Sell Stock 


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.

 solution one:

對於每一個買入的價格,採用循環查找起最大的利潤值,再從中查找出最大的利潤值
時間複雜度爲o(n^2),時間超出界限
<span style="font-size:18px;">class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int size=prices.size();
        int sale=0,buy=0,profit=0;
        for(int i=0;i!=size;++i)
        {
            buy=prices[i];
            sale=buy;
            for(int j=i+1;j!=size;++j)
            {
                if(sale<prices[j])
                    sale=prices[j];
            }
            if(profit<(sale-buy))
                profit=sale-buy;
            
        }
        return profit;
    }
};</span>

solution two:

線性時間o(n)
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        
        int size=prices.size();
        int temp;
        if(size<=1)
            return 0;
        int sale=prices[0],buy=prices[0],profit=sale-buy;
        for(int i=0;i!=size;++i)
        {
            if(buy>prices[i])
                buy=prices[i];
            sale=prices[i];
            temp=sale-buy;
            if(profit<temp)
                profit=temp;
            
        }
        if(profit<0)
            return 0;
        return profit;
    }
};


發現一篇相似的方法,只是方向不同。
http://www.cnblogs.com/remlostime/archive/2012/11/06/2757434.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章