题目
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.
实际上就是求最大的价格差,且大的数必须出现小的数后面。
从头到尾扫描,记录到相应位置的最低价格,然后不断比较差值即可。
代码:
class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.empty())
return 0;
int profit=0,min=prices[0]; //最大利润,最低价格
for(int i=1;i<prices.size();i++)
{
profit=prices[i]-min>profit?prices[i]-min:profit; //当前价格和最低价格差是否大于最大利润
min=prices[i]<min?prices[i]:min; //刷新最低价格
}
return profit;
}
};