LeetCode | 1005. Maximize Sum Of Array After K Negations, 134. Gas Station, 135. Candy

文章介绍了在给定数组中通过特定操作(k次取反)最大化数组和的方法,以及如何解决LeetCode中的两个问题:找到最大循环内旅行总和的起点和分配糖果满足孩子评级需求的最少糖果数。讨论了两种策略来解决问题,涉及迭代和比较操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1005. Maximize Sum Of Array After K Negations

Link: https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/

Description

Given an integer array nums and an integer k, modify the array in the following way:

  • choose an index i and replace nums[i] with -nums[i].

You should apply this process exactly k times. You may choose the same index i multiple times.

Return the largest possible sum of the array after modifying it in this way.

Approach

To obtain the maximum sum, we need to choose the negative integer with greater absolute value and change them into positve integers iteratively. If all the negative integers have been changed to positive integers, we need to choose the integer with the minimum absolute value and do the negations on it.

class Solution {
    public int largestSumAfterKNegations(int[] nums, int k) {
        nums = IntStream.of(nums)
                .boxed()
                .sorted((o1, o2) -> Math.abs(o2) - Math.abs(o1))
                .mapToInt(Integer::intValue).toArray();
        int len = nums.length;	    
        for (int i = 0; i < len; i++) {
            if (nums[i] < 0 && k > 0) {
                nums[i] = -nums[i];
                k--;
            }
        }
        if (k % 2 == 1) 
            nums[len - 1] = -nums[len - 1];
        return Arrays.stream(nums).sum();
    }
}

134. Gas Station

Link: https://leetcode.com/problems/gas-station/

Description

There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.

Given two integer arrays gas and cost, return the starting gas station’s index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique

Approach

Approach 1

  • Compute the rest gas after the travel to the next station of each station iteratively. Add the rest gas together and save the minimum rest sum through the iteration.
  • If the sum of the rest gas smaller than 0, which means it cannot travel around the circuit in any direaction, return -1.
  • Else if the minimum sum is larger than 0, which means the first station should be the startring station, return 0.
  • Else, loop through gas from end to start, add the rest gas to the minimum sum, and find the first index that makes the minimum sum larger than or equal to 0, return the index.

Approach 2

  • Initialize start to save the start point, curSum to save the
  • Loop through gas from start to end, compute the rest gas after the travel and add it to curSum and totalSum.
    • If the curSum smaller than 0, which means it cannot travel around in the current start point, reset curSum to 0 and set start to the next station of the current station.
  • If the totalSum smller than 0, return -1. Else, return start.
class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int sum = 0;
        int min = 0;
        for (int i = 0; i < gas.length; i++) {
            sum += gas[i] - cost[i];
            min = Math.min(sum, min);
        }
        if (sum < 0)
            return -1;
        if (min >= 0)
            return 0;
        for (int i = gas.length - 1; i > 0; i--) {
            min += gas[i] - cost[i];
            if (min >= 0)
                return i;
        }
        return -1;
    }
}

class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int curSum = 0;
        int totalSum = 0;
        int start = 0;
        for (int i = 0; i < gas.length; i++) {
            curSum += gas[i] - cost[i];
            totalSum += gas[i] - cost[i];
            if (curSum < 0) {
                start = i + 1;
                curSum = 0;
            }
        }
        if (totalSum < 0)
            return -1;
        return start;
    }
}

135. Candy

Link: https://leetcode.com/problems/candy/

Description

There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.

You are giving candies to these children subjected to the following requirements:

  • Each child must have at least one candy.
  • Children with a higher rating get more candies than their neighbors.

Return the minimum number of candies you need to have to distribute the candies to the children.

Approach

  • Initialize a int array candies to store the candies should be assigned to each child.
  • Loop through rating from start to end, compare the child with their previous child. If the current child’s rating is higher than the previous child’s, assign one more candy than the previous child’s candy count. Else, assign 1 candy to the current child.
  • Loop through rating from end to start, compare the child with their next child. If the current child’s rating is higher than the next child’s and the current child’s candy count is not already greater, assign one more candy than the next child’s candy count.
  • Return the sum of candies.

Solution

class Solution {
    public int candy(int[] ratings) {
        int[] candies = new int[ratings.length];
        candies[0] = 1;
        for (int i = 1; i < ratings.length; i++) {
            if (ratings[i] > ratings[i - 1]) 
                candies[i] = candies[i - 1] + 1;
            else
                candies[i] = 1;
        }
        for (int i = ratings.length - 2; i >= 0; i--) {
            if (ratings[i] > ratings[i + 1])
                candies[i] = Math.max(candies[i + 1] + 1, candies[i]);
        }
        return Arrays.stream(candies).sum();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值