Best Time to Buy and Sell Stock
Say you have an array for which theithelement is the price of a given stock on dayi.
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.
考点:
和选最小值和最大值不同的是:需要先买后卖!
class Solution {
public:
int maxProfit(vector<int> &prices)
{
int buy = INT_MAX, profit = 0;
for (int i = 0; i < prices.size(); i++)
{
if (prices[i] < buy) buy = prices[i];
else profit = max(profit, prices[i]-buy);
}
return profit;
}
};
//2014-2-17 update
int maxProfit(vector<int> &prices)
{
int max_profit = 0;
int lowest_point = INT_MAX;
for (int i = 0; i < prices.size(); i++)
{
if (prices[i] < lowest_point) lowest_point = prices[i];
else max_profit = max(max_profit, prices[i]- lowest_point);
}
return max_profit;
}