Say you have an array for which the i th 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)
{
int minVal=prices[];
int profit=; for(int i=;i<prices.size();++i)
{
minVal=min(prices[i],minVal);
profit=max(profit,prices[i]-minVal);
}
return profit;
}
};