代码随想录算法训练营第四十八天| ● 121. 买卖股票的最佳时机 ● 122.买卖股票的最佳时机II

买卖股票的最佳时机 

题目链接:121. 买卖股票的最佳时机 - 力扣(LeetCode)

思路:注意买卖只有一次。

暴力法,因为股票就买卖一次,那么贪心的想法很自然就是取最左最小值,取最右最大值,那么得到的差值就是最大利润:

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[i][0]表示第i天持有股票的收益,dp[i][1]表示第i天不持有股票的最大收益,最后返回dp[len-1][1],因为本题最后不持有股票肯定比持有股票挣得多:

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

买卖股票的最佳时机II 

题目链接:122. 买卖股票的最佳时机 II - 力扣(LeetCode)

思路:之前做过这道题,用的是贪心法,如下

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

但可以用动态规划来解决,与第一题的区别在于,由于第一题只能买卖一次,因此如果买入股票,那么第i天持有股票即dp[i][0]一定就是 -prices[i],而本题,因为一只股票可以买卖多次,所以当第i天买入股票的时候,所持有的现金可能有之前买卖过的利润:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int len = prices.size();
        vector<vector<int>> dp(len, vector<int>(2, 0));
        dp[0][0] -= prices[0];
        dp[0][1] = 0;
        for (int i = 1; i < len; i++) {
            dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i]); // 注意这里是和121. 买卖股票的最佳时机唯一不同的地方。
            dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
        }
        return dp[len - 1][1];
    }
};

 

posted @ 2024-03-16 15:01  SandaiYoung  阅读(2)  评论(0编辑  收藏  举报