[LeetCode] Best Time to Buy and Sell Stock

Well, there are several observations for this problem

  1. The max profit is at least 0 (buy and sell on the same day);
  2. The profit of buying on day i and selling on day j is simply prices[j] - prices[i];
  3. The maximum profit of selling the stock on day 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)