【代码随想录二刷】Day32-贪心-C++

代码随想录二刷Day32

今日任务

122.买卖股票的最佳时机II
55.跳跃游戏
45.跳跃游戏II
语言:C++

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

链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/

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

55. 跳跃游戏

链接:https://leetcode.cn/problems/jump-game/

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

45. 跳跃游戏II

链接:https://leetcode.cn/problems/jump-game-ii/
这个方法的巧妙之处在于循环终止条件的判断,因为题目保证一定会到达n-1的位置,所以我们只要保证能跳到n-2的位置即可。
可能会想问如果从n-1到n-2如果还需要跳一步的话该怎么办呢?假如此时 i 和 curPos 都是n-2,那么会进入if条件判断,res会再加1,得到正确的结果。

class Solution {
public:
    int jump(vector<int>& nums) {
        int curPos = 0;
        int nextPos = 0;
        int res = 0;
        for(int i = 0; i < nums.size() - 1; i++){
            nextPos = max(nextPos, i + nums[i]);
            if(i == curPos){
                curPos = nextPos;
                res++;
            }
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值