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

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

题目链接

p[3] - p[0] = p[3] - p[2] + p[2] - p[1] + p[1] - p[0]

差分,只有利润为正才买入。

class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        int result = 0;
        for (int i = 1; i < n; i++) {
            result += Math.max(prices[i] - prices[i - 1], 0);
        }
        return result;
    }
}

55. 跳跃游戏

题目链接

不去看细节(具体跳几步),只看覆盖范围,能不能盖住终点。

class Solution {
    public boolean canJump(int[] nums) {
        int n = nums.length;
        int cover = 0; // 覆盖范围
        for (int i = 0; i <= cover; i++) {
            cover = Math.max(cover, i + nums[i]);
            if (cover >= n - 1) {
                return true;
            }
        }
        return false;
    }
}

45. 跳跃游戏 II

题目链接

每次要最大的覆盖范围,直到覆盖终点.

class Solution {
    public int jump(int[] nums) {
        int n = nums.length;

        if (n == 1) { // 只有 1 个元素,不用动
            return 0;
        }

        int cur = 0, next = 0; // 当前覆盖范围和下一个覆盖范围
        int result = 0;
        for (int i = 0; i < n; i++) {
            next = Math.max(next, i + nums[i]);
            if (i == cur) { // 如果已经满一轮
                result++; // 满一轮 result 就加 1
                if (next >= n - 1) { // next 已经覆盖终点了
                    break;
                }
                cur = next; // next 还没覆盖终点,开始跑下一轮
            }
        }
        return result;
    }
}

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

题目链接

两次贪心:

  1. 优先选负数取反。
  2. 全部变为正数后,选数组里最小的正数取反来消耗掉剩余的 k。

绝对值排序,更方便取最小正数(即最后一个元素)。

[-3, 2, -1, 0]

class Solution {
    public int largestSumAfterKNegations(int[] nums, int k) {
        int n = nums.length;

        // 转换为Integer数组进行排序
        Integer[] numsWrapper = Arrays.stream(nums).boxed().toArray(Integer[]::new);
        
        Arrays.sort(numsWrapper, new Comparator<Integer>() {
            @Override
            public int compare(Integer a, Integer b) {
                // 按绝对值降序:b在前,a在后
                return Integer.compare(Math.abs(b), Math.abs(a));
            }
        });
        
        // 转换回int数组
        for (int i = 0; i < nums.length; i++) {
            nums[i] = numsWrapper[i];
        }                  

        for (int i = 0; i < n; i++) {
            if (nums[i] < 0 && k > 0) {
                nums[i] *= -1;
                k--;
            }
        }
        if (k > 0 && k % 2 == 1) { // 如果 k 还有剩余且为奇数,对绝对值最小的正数操作
            nums[n - 1] *= -1;
        }

        // 求和
        int sum = 0;
        for (int x : nums) {
            sum += x;
        }
        return sum;
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值