代码随想录算法训练营day28 | 122.买卖股票的最佳时机II、55. 跳跃游戏、45、跳跃游戏Ⅱ、1005.K次取反后最大化的数组和

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

点击查看代码
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int result = 0;
        for(int j = 1; j < prices.size(); ++j) {
            if(prices[j] - prices[j - 1] > 0)
                result += (prices[j] - prices[j - 1]);
        }
        return result;
    }
};
  1. 跳跃游戏
点击查看代码
class Solution {
public:
    bool canJump(vector<int>& nums) {
        //maxIndex记录当前可到达的最远下标
        int maxIndex = nums[0];
        for(int i = 0; i <= maxIndex; ++i) {
            //在覆盖范围内每走一步就更新覆盖范围
            maxIndex = max(maxIndex, i + nums[i]);
            //maxIndex若已经能到达末尾了,则可提前返回
            if(maxIndex >= nums.size() - 1) return true;
        }
        //循环内没有返回则说明最终maxIndex覆盖不到数组的最后一个位置,返回false
        return false;
    }
};

45、跳跃游戏Ⅱ

点击查看代码
class Solution {
public:
    int jump(vector<int>& nums) {
        if(nums.size() == 1) return 0;
        int result = 1;
        int curmaxIndex = nums[0];
        if(curmaxIndex >= nums.size() - 1) return result;
        int nextmaxIndex = INT_MIN;
        for(int i = 1; i <= curmaxIndex; ++i) {
            //下一步可以到达的最远下标
            nextmaxIndex = max(nextmaxIndex, i + nums[i]);
            if(nextmaxIndex >= nums.size() - 1) return result + 1;
            //说明curmaxIndex范围内的元素跳一步无法到达最末端
            //故需要多跳一步跳到下一个覆盖范围内继续寻找
            if(i == curmaxIndex) {
                curmaxIndex = nextmaxIndex;
                ++result;
            }
        }
        return result;
    }
};

1005.K次取反后最大化的数组和

点击查看代码
class Solution {
public:
    int largestSumAfterKNegations(vector<int>& nums, int k) {
        sort(nums.begin(), nums.end());
        int i = 0;
        while(i < nums.size() && nums[i] < 0 && k > 0) {
            nums[i] = -nums[i];
            ++i;
            --k;
        }
        //k > 原数组中负数的个数时
        if(k % 2) {
            sort(nums.begin(), nums.end());
            //nums[0]为此时最小的正数或零
            nums[0] = -nums[0];
        }
        int sum = 0;
        for(int j = 0; j < nums.size(); ++j) sum += nums[j];
        return sum;
    }
};
posted @ 2025-03-11 20:52  coder小杰  阅读(19)  评论(0)    收藏  举报