代码随想录算法训练营第三十二天 | 122.买卖股票的最佳时机II,55. 跳跃游戏,45.跳跃游戏II

代码随想录算法训练营第三十二天 | 122.买卖股票的最佳时机II,55. 跳跃游戏,45.跳跃游戏II

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

思路:

  1. 贪心
  2. 局部最优:收集每天的正利润
  3. 全局最优:求得最大利润
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0;
        for(int i = 1; i < prices.size(); ++i){
            if(prices[i] - prices[i-1] > 0) res += prices[i] - prices[i-1];
        }
        return res;
    }
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)

1.2 55. 跳跃游戏

思路:

  1. 关键在于可跳的覆盖范围
  2. 局部最优解:每次取最大跳跃步数(取最大覆盖范围)
  3. 整体最优解:最后得到整体最大覆盖范围,看是否能到终点
class Solution {
public:
    bool canJump(vector<int>& nums) {
        int maxL = 0;
        for(int i = 0; i < nums.size(); ++i){
            if(maxL < i) return false;
            maxL = max(maxL, i+nums[i]);
        }
        return true;
    }
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(1)

1.3 45.跳跃游戏II

思路:

  1. 局部最优:当前可移动距离尽可能多走,如果还没到终点,步数再加一
  2. 整体最优:一步尽可能多走,从而达到最小步数
  3. 需要记录两个值,当前这一步的最大覆盖和下一步最大覆盖
  4. 当走到当前最远的时候,考虑步数+1,使用下一步最大范围
class Solution {
public:
    int jump(vector<int>& nums) {
        if(nums.size() == 1) return 0;
        int curDistance = 0;
        int nextDistance = 0;
        int step = 0;
        for(int i = 0; i < nums.size(); ++i){
            nextDistance = max(nextDistance, nums[i] + i);
            if(curDistance == i){
                step++;
                curDistance = nextDistance;
            }
            if(curDistance >= nums.size()-1) break;
        }
        return step;
    }
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(1)

你可能感兴趣的:(刷题打卡,算法,游戏,c++)