暴力超时版本

  1. class Solution {
  2. public:
  3. int maxProfit(vector<int>& prices) {
  4. if(prices.size() <=0){
  5. return 0;
  6. }
  7. int n = prices.size();
  8. int dp1 = 0;
  9. for (int i = 0; i < n; i++)
  10. {
  11. dp1 = max(dp1,
  12. maxRange(prices, 0, i) + maxRange(prices, i, n));
  13. }
  14. return dp1;
  15. }
  16. int maxRange(vector<int>& prices, int start, int end){
  17. int dp = 0;
  18. int minP = 0;
  19. minP = prices[start];
  20. for (int i = start; i < end; i++)
  21. {
  22. dp = max(dp , prices[i] - minP);
  23. if(prices[i] < minP){
  24. minP = prices[i];
  25. }
  26. }
  27. return dp;
  28. }
  29. };

优化版本

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size() <=0){
            return 0;
        }
        int n = prices.size();
        vector<int> min_f(n+1, 0);
        vector<int> max_p(n+1, 0);
        vector<int> max_b(n+1, 0);
        min_f[0] = prices[0];
        for(int i = 1; i<prices.size(); i++){
            min_f[i] = min(prices[i], min_f[i - 1]);
        }
        max_b[prices.size() - 1] = prices[prices.size() - 1];
        max_p[n-1] = 0;
        for(int i = prices.size() - 2; i>=0; i--){
            max_b[i] = max(prices[i], max_b[i + 1]);
            max_p[i] = max(max_b[i] - prices[i],  max_p[i+1]);
        }
        int dp1 = 0;
        for (int i = 0; i < n -1; i++)
        {
            dp1 = max(dp1, prices[i] - min_f[i] +  max_p[i]);
        }
        dp1 = max(dp1, prices[n-1]- min_f[n-1] + max_p[n-1]);
        return dp1;
    }

};