力扣第26天----第122题、第55题、第45题

力扣第26天----第122题、第55题、第45题

一、第122题–买卖股票的最佳时机 II

​ 赚钱的时候,把每天赚的钱加起来,就是最终的钱。没有任何难度!

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;
    }
};

二、第55题–跳跃游戏

​ 这个题,属于见过就会做。实现上没难度,分析起来花点时间,下次见到类似的能做出来。核心就是:1)根据i + nums[i]做是否满足的判断;2)for循环end的位置更新为max(end, i + nums[i])。

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

三、第45题–跳跃游戏 II

​ 有点难,看了答案才做出来的。逻辑不好梳理,希望下次做,能做出来。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值