算法day24-贪心(2)

目录

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

一、买卖股票的最佳时机

 https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/?envType=problem-list-v2&envId=8At1GmaZ

 

class Solution {
    public int maxProfit(int[] prices) {
        int sum = 0;
        for(int i=0; i<prices.length-1; i++){
            if(prices[i+1] > prices[i]){        //如果后一天大于当天,则卖-买
                sum += prices[i+1]-prices[i];
            }
        }
        return sum;
    }
}

 

二、跳跃游戏

 https://leetcode.cn/problems/jump-game/description/?envType=problem-list-v2&envId=8At1GmaZ

 

class Solution { 
    public boolean canJump(int[] nums) {
        int maxJump = 0;

        // 遍历数组,更新最大可到达的位置
        for (int i = 0; i < nums.length; i++) {
            // 如果当前位置无法到达,则返回 false
            if (i > maxJump) {
                return false;
            }
            // 更新最大可到达的位置
            maxJump = Math.max(maxJump, i + nums[i]);

            // 如果最大可到达的位置已经超过或到达最后一个位置,则返回 true
            if (maxJump >= nums.length - 1) {
                return true;
            }
        }
        return false;
    }
}

 

三、跳跃游戏II

 https://leetcode.cn/problems/jump-game-ii/description/?envType=problem-list-v2&envId=8At1GmaZ

 

class Solution {
    public int jump(int[] nums) {
        int jumps = 0;
        int maxReach = 0;
        int end = 0;
        for(int i=0; i<nums.length-1; i++){
            //维护每个i对应的最大的maxReach
            maxReach = Math.max(maxReach, nums[i]+i);
            //当到达end时,这时候需要选择跳跃
            if(i == end){
                jumps++;
                end = maxReach;
            }
        }
        return jumps;
    }
}

 

四、K次取反后最大化的数组和

 https://leetcode.cn/problems/maximize-sum-of-array-after-k-negations/description/?envType=problem-list-v2&envId=8At1GmaZ

 

import java.util.Arrays;

class Solution {
    public int largestSumAfterKNegations(int[] nums, int k) {
        // 先对数组进行排序,负数会被排到前面
        Arrays.sort(nums);
        
        // 反转负数,尽量将负数转换为正数
        for (int i = 0; i < nums.length; i++) {
            if (k > 0 && nums[i] < 0) {
                // 反转负数
                nums[i] = -nums[i];
                k--;
            }
        }
        
        // 如果k剩余且为奇数,则翻转最小的元素(最小的元素可能是正数或反转后的负数)
        if (k % 2 != 0) {
            // 如果剩下的k为奇数,则选择数组中的最小值再翻转一次
            int minIndex = 0;
            for (int i = 1; i < nums.length; i++) {
                if (nums[i] < nums[minIndex]) {
                    minIndex = i;
                }
            }
            // 翻转最小的元素
            nums[minIndex] = -nums[minIndex];
        }
        
        // 计算最终的和
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        
        return sum;
    }
}

 

posted @ 2025-05-24 23:49  筱倩  阅读(9)  评论(0)    收藏  举报