标签:
Well, there are several observations for this problem
0
(buy and sell on the same day);i
and selling on day j
is simply prices[j] - prices[i]
;j
is prices[j] - min_{i=1,2,...,j}prices[i]
.Combining these observations together, the following code is easy to understand. I wonder whether the following solution can be called DP since it is just very intuitive.
1 int maxProfit(vector<int>& prices) { 2 if (prices.empty()) return 0; 3 int min_price = prices[0]; // maintain the minimum price that has been seen 4 int max_profit = 0; // maintain the maximum profit that has been seen 5 for (int i = 1; i < prices.size(); i++) { 6 min_price = min(min_price, prices[i]); // update the min price 7 max_profit = max(max_profit, prices[i] - min_price); // update the max profit 8 } 9 return max_profit; 10 }
[LeetCode] Best Time to Buy and Sell Stock
标签:
原文地址:http://www.cnblogs.com/jcliBlogger/p/4548105.html