代码随想录算法训练营Day48 | 121. 买卖股票的最佳时机 122.买卖股票的最佳时机II

发布于:2024-05-25 ⋅ 阅读:(131) ⋅ 点赞:(0)

代码随想录算法训练营Day48 | 121. 买卖股票的最佳时机 122.买卖股票的最佳时机II

LeetCode 121. 买卖股票的最佳时机

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

思路:
取左边最小,更新右边最大。

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

//dp

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        vector<vector<int>> dp(n,vector<int>(2));
        dp[0][0] = -prices[0];
        dp[0][1] = 0;

        for(int i=1; i<n; 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[n-1][1];
    }
};

注意 :

  1. dp 分别为第i天没股票和第i天有股票的状态

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

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

思路:
贪心简单

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

//dp

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if (prices.size()==1) return 0;
        int n = prices.size();
        vector<vector<int>> dp(n, vector<int>(2));
        dp[0][0] = -prices[0];
        dp[0][1] = 0;

        for(int i=1; i<n; 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[n-1][1];
    }
};

注意 :

  1. dp同理

网站公告

今日签到

点亮在社区的每一天
去签到