原题:
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 maxprofit = INT_MIN;
int maxprice = prices[prices.size()-1];
for(int i = prices.size()-1; i >= 0; i--){
maxprice = prices[i]>maxprice?prices[i]:maxprice;
maxprofit = maxprofit>(maxprice-prices[i])?maxprofit:maxprice-prices[i];
}
return maxprofit;
}
};