代码随想录训练营第四十八天|LeetCode 121、122

LeetCode 121买卖股票的最佳时机

题目链接:121.买卖股票的最佳时机

//动规
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        //0:持有    1:不持有
        vector<vector<int>> dp(prices.size(), vector<int>(2, 0));
        dp[0][0] = -prices[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];
    }
};
//贪心
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int ans = 0;
        int minPrice = prices[0];
        for (int i = 1; i < prices.size(); ++i) {
            if (prices[i] > minPrice) {
                ans = max(ans, prices[i] - minPrice);
            }
            else minPrice = prices[i];
        }
        return ans;
    }
};

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

题目链接:122.买卖股票的最佳时机II

//贪心
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int ans = 0;
        int minPrice = prices[0];
        for (int i = 1; i < prices.size(); ++i) {
            if (prices[i] > minPrice) {
                ans += prices[i] - minPrice;
            }
            minPrice = prices[i];
        }
        return ans;
    }
};
//动规
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        //0:持有    1:不持有
        vector<vector<int>> dp(2, vector<int>(2, 0));
        dp[0][0] = -prices[0];
        for (int i = 1; i < prices.size(); ++i) {
            dp[i % 2][0] = max(dp[(i - 1) % 2][0], -prices[i] + dp[(i - 1) % 2][1]);
            dp[i % 2][1] = max(dp[(i - 1) % 2][1], dp[(i - 1) % 2][0] + prices[i]);
        }
        return dp[(prices.size() - 1) % 2][1];
    }
};

你可能感兴趣的:(LeetCode刷题,leetcode,算法,动态规划,贪心算法)