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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值