代码随想录Day32

57 阅读1分钟

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

力扣题目链接

class Solution {
public:
    // 贪心算法
    // 把利润分解为每天为单位的维度,而不是从整体去考虑。
    // 局部最优:收集每天的正利润,全局最优:求得最大利润。
    int maxProfit(vector<int>& prices) {
        int result = 0;
        for (int i = 1; i < prices.size(); ++i) {
            result += max(prices[i] - prices[i - 1], 0);
        }
        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 curDistance = 0;    // 当前覆盖的最远距离下标
        int ans = 0;            // 记录走的最大步数
        int nextDistance = 0;   // 下一步覆盖的最远距离下标
        for (int i = 0; i < nums.size() - 1; i++) { // 注意这里是小于nums.size() - 1,这是关键所在
            nextDistance = max(nums[i] + i, nextDistance); // 更新下一步覆盖的最远距离下标
            if (i == curDistance) {                 // 遇到当前覆盖的最远距离下标
                curDistance = nextDistance;         // 更新当前覆盖的最远距离下标
                ans++;
            }
        }
        return ans;
    }
};