day32打卡

day32打卡

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

解法,贪心:局部,收集每天的正利润-》整体,获取最大利润

从第0天到第3天,利润为:price[3] - price[0],也可以是(price[3] - price[2]) + (price[2] - price[1]) + (price[1] - price[0])。最终利润也就是把每天的利润加起来,题目要求获得最大的利润,我们只把大于0的利润相加即可。

day32打卡_第1张图片

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

55. 跳跃游戏

思路,贪心:局部,每一步取最大覆盖范围-》整体,最终获得最大覆盖范围

跳跃几步是无所谓的,重要的是能够覆盖的范围能不能覆盖到终点。

我们每走一步就更新覆盖的最远距离,然后判断它能否覆盖到终点即可。

前提是i必须是在len的范围中移动。

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int len = 0;
        for(int i = 0; i < nums.size(); i++)
        {
            //控制i要在len的范围内
            if(i <= len)
            {
                if(len >= nums.size()-1) return true;
                //len和当前位置+nums[i],比谁覆盖的远
                len = max(len, i + nums[i]);
            }
        }
        return false;
    }
};

45. 跳跃游戏 II

思路,贪心:

以最小的步数,跳跃最大的范围。

class Solution {
public:
    int jump(vector<int>& nums) {
        //当前最远距离,下一步最远距离,跳跃次数
        int curEnd = 0, nextEnd = 0, count = 0;
        for(int i = 0; i < nums.size()-1; i++)
        {
            nextEnd = max(nextEnd, i + nums[i]);
            if(i == curEnd)
            {
                curEnd = nextEnd;
                count++;
            }
        }
        return count;
    }
};

你可能感兴趣的:(代码,算法,leetcode)