代码随想录刷题第32天

今天继续贪心算法的学习。第一题是买卖股票的最佳时机https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/description/,题目很唬人,但事实上就是遍历一遍数组,求出所有利润为正的情况加和就行,代码很简单。

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

第二题是跳跃游戏https://leetcode.cn/problems/jump-game/,自己的想法是只要将对应元素大小作为跳跃距离,最后的跳跃距离能够超出数组大小则一定可以到达末尾。但是写出的代码始终不能ac。看了卡哥的思路,才发现是用覆盖范围确定最后一个元素是否能被覆盖掉。

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

第三题是跳跃游戏的进阶https://leetcode.cn/problems/jump-game-ii/description/,求出到达终点的最少步数。就是看覆盖范围到达末尾的最小更新次数。

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

    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值