Say you have an array for whichITh element is the price of a given stock on dayI.
If you were only permitted to complete at most one transaction (ie, buy one and every one share of the stock), design an algorithm to find the maximum profit.
At the beginning, I thought it was the maximum value minus the minimum value. However, because the purchase occurred before the sale, the minimum value buy and the maximum value sell occurs only when the minimum value is before the maximum value.
The idea of this question is: record the first minimum value of the time, and then max (current element-the first minimum value ).
class Solution {public: int maxProfit(vector<int> &prices) { if(prices.size() == 0) return 0; int res = 0, minv = prices[0]; for(int i = 1; i < prices.size(); ++ i){ res = max(res,prices[i]-minv); minv = min(prices[i],minv); } return res; }};
You can also consider using dynamic planning for this question.
Set the decision variable to DP [I], which indicates the maximum profit sold by I elements.
The state transition equation is
DP [I + 1] = Prices [I + 1]-Prices [I] + max (0, DP [I])
Since the previous DP [I] is not used after DP [I + 1], you only need a state variable to update it continuously.
class Solution {public: int maxProfit(vector<int> &prices) { int dp = 0, res = 0; for(int i = 1; i < prices.size(); ++ i){ dp = prices[i]-prices[i-1] + max(0,dp); res = max(res,dp); } return res; }};