Sword refers to Offer 63-the maximum profit of the stock C++

Title description

Insert picture description here

Solution dp

1. The meaning of the
dp array dp[i]: The maximum profit can be obtained by selling on the i day
2. The
dp equation dp[i] = max(dp[i-1], price[i] -min (price[0]~price [i])
3. Initial value
dp[0] = 0

class Solution {
    
    
public:
    int maxProfit(vector<int>& prices) {
    
    
        if(prices.size() == 0) return 0;
        int cMin = prices[0];
        int len = prices.size() - 1;
        vector<int> dp (len + 1, 0);
        for(int i = 1; i <= len; i++) {
    
    
            cMin = min(cMin,prices[i]);
            dp[i] = max(dp[i - 1], prices[i] - cMin);
        }
        return dp[len];
    }
};

Insert picture description here
Time complexity O(N)
space complexity O(N)
optimization:

class Solution {
    
    
public:
    int maxProfit(vector<int>& prices) {
    
    
        if(prices.size() == 0) return 0;
        int cMin = prices[0];
        int ans = 0;
        int len = prices.size() - 1;
        for(int i = 1; i <= len; i++) {
    
    
            cMin = min(cMin,prices[i]);
            ans = max(ans, prices[i] - cMin);
        }
        return ans;
    }
};

Insert picture description here
Time complexity O(N)
Space complexity O(1)

Guess you like

Origin blog.csdn.net/qq_42883222/article/details/112790669