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.
思路:假设第i天买入了股票,则最大利润为i+1~n中的股票最高值-prices[i]。
class Solution { public: int maxProfit(vector<int> &prices) { int res = 0; if(prices.empty()) { return res; } int i,j,len=prices.size(); int max = INT_MIN; for(i=len-1; i>=0; --i) { max = (max > prices[i] ? max : prices[i]); res = (res > max-prices[i] ? res : max-prices[i]); } return res; } };