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),
solution one:
<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:
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;
}
};