代码随想录算法训练营第四十九天| LeetCode121. 买卖股票的最佳时机 22.买卖股票的最佳时机II

121. 买卖股票的最佳时机

题目:力扣

//贪心
class Solution {
public:
    int maxProfit(vector& prices) {
        int ans = 0;
        int low = INT_MAX;
        for(int i = 0; i < prices.size(); ++i){
            low = min(low,prices[i]);
            ans = max(ans,prices[i] - low);
        }
        return ans;
    }
};
//动态规划
class Solution {
public:
    int maxProfit(vector& prices) {
        vector > dp(prices.size(),vector(2,0));
        dp[0][0] -= prices[0];
        dp[0][1] = 0;
        for(int i = 1; i < prices.size(); ++i){
            dp[i][0] = max(dp[i-1][0], - prices[i]);
            dp[i][1] = max(dp[i-1][1],dp[i-1][0] + prices[i]);
        }
        return dp[prices.size()-1][1];
    }
};

122.买卖股票的最佳时机II

题目:力扣

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

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

总结

题型:动态规划,买卖股票

你可能感兴趣的:(代码随想录算法训练营,leetcode,算法,动态规划,c++)