leetcode打卡#day35 122. 买卖股票的最佳时机 II、55. 跳跃游戏、45. 跳跃游戏 II

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

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int profit;
        int total = 0;
        //把前后2天的收益都记录下来, 然后把收益为正的都加起来就是最大利润
        for (int i = 1; i < prices.size(); i++) {
            profit = prices[i] - prices[i-1];
            if (profit > 0) {
                total += profit;
            }
        }
        return total;
    }
};

55. 跳跃游戏

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int n = nums.size();
        int k = 0; //k表示累计能跳到的最大距离吧
        for (int i = 0; i < n; ++i){
            if (i > k) return false;  // i > k 表示不能成功跳到最后一个位置
            k = max(k, i+ nums[i]);
        }
        //如果成功跳过该循环,则表示能成功跳到最后一个位置
        return true;
    }
};

45. 跳跃游戏 II

class Solution {
public:
    int jump(vector<int>& nums) {
        if (nums.size() == 1) return 0;
        int curDistance = 0;//当前能覆盖到的最远距离
        int ans = 0;//记录能走的最大步数
        int nextDistance = 0;//下一步覆盖最远距离
        for (int i = 0; i < nums.size(); i++) {
            //下一步能达到的最远距离
            nextDistance = max(nums[i]+i, nextDistance);
            if (i == curDistance) {
                ans++;
                curDistance = nextDistance;
                if (nextDistance >= nums.size()-1) return ans;
            }
        }
        return ans;
    }
};
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值