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.
Best Time to Buy and Sell Stock III
会用到!
//跟随式,保证min在前,用当前的比较。
// profit = max(profit,prices[i] - min_val)
// min_val = min(prices[i],min_val);
int maxProfit(vector<int> &prices) {
if(prices.size() <= 1)return 0;
int min_val = prices[0];
int profit = 0;
for(int i = 1;i < prices.size();i++)
{
if(min_val > prices[i])
{
min_val = prices[i];
}
if(profit < prices[i] - min_val)
{
profit = prices[i] - min_val;
}
}
return profit;
}