代码随想录算法训练营第32天| 122.买卖股票的最佳时机II 55. 跳跃游戏 45.跳跃游戏II

  • 今日学习的文章链接,或者视频链接

第八章 贪心算法 part02

  • 自己看到题目的第一想法

  • 看完代码随想录之后的想法

122

动态规划:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        //dp[i][0]:第i天不持有股票能获得的最大利润
        //dp[i][1]:第i天持有股票能获得的最大利润
        vector<vector<int>> dp(n, vector<int>(2));
        for (int i = 0; i < n; i++) {
            if (i - 1 == -1) {
                // base case
                dp[i][0] = 0;
                dp[i][1] = -prices[i];
                continue;
            }
            dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i]);//之前就不持有或者i天卖出
            dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i]);//之前就买入或者i天买入
        }
        return dp[n - 1][0];
    }
};

贪心(贪每天的利润):

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        vector<int> profit_day(n-1,0);
        for(int i =1;i<n;i++){
            int cur = prices[i]-prices[i-1];
            if (cur>0){
                profit_day[i-1]=cur;
            }
        }
        int result = 0;
        for(auto profit:profit_day){
            result+=profit;
        }
        return result;
    }
};

55

贪心求覆盖范围:

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int n = nums.size();
        int farthest = 0;
        for(auto i=0;i<=farthest;i++){
            farthest = max(farthest,i+nums[i]);
            if(farthest >= n-1) {
                return true;
            }
        }
        return false;
    }
};

45

class Solution {
public:
    int jump(vector<int>& nums) {
        int cur = 0,next = 0;
        int result = 0;
        for(auto i=0;i<nums.size();i++){
            next = max(next,i + nums[i]);
            if(i==cur&&(cur!=nums.size()-1)){
                result++;
                cur = next;
            }
        }
        return result;
    }
};

  • 自己实现过程中遇到哪些困难

  • 今日收获,记录一下自己的学习时长

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值