Day28 买卖股票的最佳时机 跳跃游戏 跳跃游戏 II K 次取反后最大化的数组和

贪心算法 part02
122. 买卖股票的最佳时机 II - 力扣(LeetCode)

求最大利润 将每天的正利润加和

    public int maxProfit(int[] prices) {
        int totalPrices = 0;
        for(int i=0;i<prices.length;i++){
            if(i<prices.length-1&&prices[i+1]>prices[i]){
                totalPrices += prices[i+1]-prices[i];
            }
        }
        return totalPrices;
    }
55. 跳跃游戏 - 力扣(LeetCode)

问题就转化为跳跃覆盖范围究竟可不可以覆盖到终点

每移动一个单位,就更新最大覆盖范围。

贪心算法局部最优解:每次取最大跳跃步数(取最大覆盖范围),整体最优解:最后得到整体最大覆盖范围,看是否能到终点

    public boolean canJump(int[] nums) {
//        遍历当前值范围的数 并且在范围之内加上当前值的范围 能够到达数组的长度 即能跳到终点
        int cover = 0;
//        更新cover范围 并且在此范围遍历
        for (int i = 0; i <= cover; i++) {
            cover = Math.max(i + nums[i], cover);
            if (cover >= nums.length - 1) {
                return true;
            }
        }
        return false;
    }
45. 跳跃游戏 II - 力扣(LeetCode)

在这里插入图片描述

    public int jump(int[] nums) {
        int next = 0;
        int count = 0;
        int cur =0;
//      在数的范围内找到覆盖范围最大的数 当遍历到范围的最后一个值 count++ 直到cur 遍历到数组末尾
        for(int i=0;i<nums.length;i++){
//           1. 在数的范围内找到覆盖范围最大的数  //在可覆盖区域内更新最大的覆盖区域
            next = Math.max(next, i+nums[i]);
//           2. 当遍历到范围的最后一个值 count++
            if(i == cur){
                if(cur !=nums.length-1){
                    count++;
                    cur =next;
                    if(cur >= nums.length-1){
                        break;
                    }
                }else {
                    break;
                }
            }
        }
        return count;
    }
1005. K 次取反后最大化的数组和 - 力扣(LeetCode)

贪心思想 : 存在负数取反 选择绝对值最大的取反 同理都大于0 选择最小的正数取反 从而局部最优到整体最优

    public int largestSumAfterKNegations(int[] nums, int k) {
        int count = 0;
        Arrays.sort(nums);
        for(int i = 0;i<nums.length;i++){
            if(k>0&&nums[i]<0){
                nums[i] = -nums[i];
                k--;
            }
        }
//        将负数转为正数的数组 重新排序
        Arrays.sort(nums);
        if(k%2==1){
            nums[0] = -nums[0];
        }
        for (Integer i : nums){
            count =count+i;
        }
        return count;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值