代码随想录28| 122.买卖股票的最佳时机II, 55. 跳跃游戏, 45.跳跃游戏II

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

链接地址

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

55. 跳跃游戏

链接地址

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

45.跳跃游戏II

链接地址

class Solution {
public:
    int jump(vector<int>& nums) {
        //记录当前位置
        int cur = 0;
        //记录下一条的覆盖范围
        int next = 0;
        //记录结果
        int result = 0;
        for (int i = 0; i < nums.size(); i++) {
            next = max(i + nums[i], next);
            if (cur == i) {
                if (cur != nums.size() - 1) {
                    result++;
                    cur = next;
                    if (cur >= nums.size() - 1) break;
                } else break;
            }
        }
        return result;

    }
};

你可能感兴趣的:(代码随想录刷题,算法,leetcode,c++)