代码随想录算法训练营第三十四天|贪心算法 part03|1005.K次取反后最大化的数组和 ● 134. 加油站● 135. 分发糖果

●  1005.K次取反后最大化的数组和 Maximize Sum Of Array After K Negations - LeetCode

sort 了两次

class Solution {
    public int largestSumAfterKNegations(int[] nums, int k) {
        Arrays.sort(nums);
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] < 0 && k > 0) {
                nums[i] = -1 * nums[i];
                k--;
            }
        }
        Arrays.sort(nums);
        if (k % 2 == 1) nums[0] *= -1;
        for (int n : nums) {
            sum += n;
        }
        return sum;
    }
}

●  134. 加油站 

●  135. 分发糖果Candy - LeetCode

1.右孩子比左孩子得分高 

if (rating[i] > rating[i - 1)

        candy[i] = candy[i - 1] + 1;

2. 左孩子比右孩子得分高

if (rating[i] > rating[i + 1])

        candy[i] = candy[i + 1] + candy[i];

int[] canday(rating.size(), 1)

for (int i = 1; i < rating.size(); i++)

        if (rating[i] > rating[i - 1])

                candy[i] = candy[i - 1] + 1;

for (int i = rating.length - 1; i >= 0; i--)

for (int i = 0; ii < rating,length; i++)

        res += candy[i];

class Solution {
    public int candy(int[] ratings) {
        int n = ratings.length;
        int[] candy = new int[n];
        candy[0] = 1;
        for (int i = 1; i < n; i++) {
            // if (ratings[i] > ratings[i - 1]) {
            //     candy[i] = candy[i - 1] + 1;
            // }
            candy[i] = (ratings[i] > ratings[i - 1]) ? candy[i - 1] + 1 : 1;
        }
        for (int i = n - 2; i >= 0; i--) {
            if (ratings[i] > ratings[i + 1]) {
                candy[i] = Math.max(candy[i], candy[i + 1] + 1);
            }
        }
        int sum = 0;
        for (int c : candy) {
            sum += c;
        }
        return sum;
    }
}

       

    

      

你可能感兴趣的:(代码随想录算法训练营,贪心算法,算法)