LeetCode第5天 | 动态规划 | 20220718

LeetCode第5天 | 动态规划 | 20220718

本文章参考了他人的笔记,仅供自己学习复习使用。


【第一题】123. 买卖股票的最佳时机 III

1.1 读题

在这里插入图片描述
在这里插入图片描述

1.2 解题

代码1.1:最原始的思路,但是执行错误

#include <vector> 
class Solution {
public:
    vector<int> profitList;
    void AddprofitList(vector<int>& prices, vector<int>& profitList){
        int pre=0,p=1;
        int len = prices.size();
        int tmpSum = 0;
        int count = 0;
        for(int i = 0;i<len;i++){
            int ppre = pre;

            if(prices[p]>prices[p-1]){
                tmpSum = prices[p]-prices[pre];
                p++;
            }
            else{
                pre = p;
                p++;
            }
            if(ppre !=pre && tmpSum > 0){
                count++;
                profitList.emplace_back(tmpSum);
            }
        }

        sort(profitList.rbegin(),profitList.rend());
    }
    int maxProfit(vector<int>& prices) {
        AddprofitList(prices, profitList);
        int profit=0;
        for(int i =0;i<2;i++){
            if(profitList[i]>0){
                profit += profitList[i];
            }else{
                break;
            }
            
        }
        return profit;
    }
};

代码1.2:参考liweiwei的解答 并改写为c++

class Solution {
public:
    int maxProfit(vector<int> prices) {
        int len = prices.size();
        if (len < 2) {
            return 0;
        }

        // dp[i][j] ,表示 [0, i] 区间里,状态为 j 的最大收益
        // j = 0:什么都不操作
        // j = 1:第 1 次买入一支股票
        // j = 2:第 1 次卖出一支股票
        // j = 3:第 2 次买入一支股票
        // j = 4:第 2 次卖出一支股票

        vector<int> dp(5);
        dp[1] = -prices[0];
        // 3 状态都还没有发生,因此应该赋值为一个不可能的数
        dp[3] = -2147483648;

        for (int i = 1; i < len; i++) {
            dp[0] = 0;
            dp[1] = max(dp[1], dp[0] - prices[i]);
            dp[2] = max(dp[2], dp[1] + prices[i]);
            dp[3] = max(dp[3], dp[2] - prices[i]);
            dp[4] = max(dp[4], dp[3] + prices[i]);
        }
        return max(0, max(dp[2], dp[4]));
    }
};

1.3 知识补充 | java中的Integer.MIN_VALUE

liweiwei的解答java代码原为:
在这里插入图片描述

在JDK中,整形类型是有范围的,最大值为Integer.MAX_VALUE,即2147483647,最小值为Integer.MIN_VALUE -2147483648。这两个数字刚好是int的范围。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值