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