Day34|leetcode 1005.Maximized array sum after K times inversion, 134. Gas station, 135. Distributing candy

leetcode 1005. The array sum maximized after K times inversion

Topic Link: 1005. Maximized Array Sum After K Negations - LeetCode

Video link: Greedy algorithm, isn't this common sense? Can you still call it greedy? LeetCode: 1005. The array sum maximized after K inversions_哔哩哔哩_bilibili

topic overview

Given an array of integers  nums and an integer  k , modify the array as follows:

  • Select a subscript  i and  nums[i] replace with  -nums[i] .

Repeat this process exactly  k times. The same subscript can be selected multiple times  i .

After modifying an array in this way, return  the largest sum possible for the array  .

Example 1:

Input: nums = [4,2,3], k = 1
 Output: 5
 Explanation: Select subscript 1, nums becomes [4,-2,3].

train of thought

The idea of ​​this question is very simple. If there are negative numbers in the integer array, then flip the number with the largest absolute value in the negative number first. If there are no negative numbers, but the number of flips has not been used up, then flip the smallest positive number in the array. Only in this way can we ensure that the sum returned at the end is the maximum value.

Code

class Solution {
static bool cmp(int a,int b) {
    return abs(a) > abs(b);
}
public:
    int largestSumAfterKNegations(vector<int>& nums, int k) {
        sort(nums.begin(),nums.end(),cmp);
        for(int i = 0;i < nums.size();i++) {
            if(nums[i] < 0 && k >0) {
                nums[i] *= -1;
                k--;
             }
        }
        if(k % 2 == 1) nums[nums.size() - 1] *= -1;
        int result = 0;
        for(int a : nums) result += a;
        return result;

    }
};

Leetcode 134. Gas station

Topic Link: 134. Gas Station - LeetCode

Video link: Greedy algorithm, you have to work hard to run the full distance! LeetCode: 134. Gas station_哔哩哔哩_bilibili

topic overview

There is a gas station on a ring road  n , and the first  i gas station has gasoline  gas[i] liters.

You have a car with unlimited fuel tank capacity, and it takes gasoline  liters to drive from the first gas station to the first gas station . You start off from one of the gas stations, starting with an empty tank. i  i+1 cost[i] 

Given two integer arrays  gas and  cost , if you can drive around the loop in sequence, return the number of the gas station at the time of departure, otherwise return  -1 . If a solution exists,   it is  guaranteed to be unique  .

Example 1:

Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
 Output: 3
 Explanation:
 Starting from gas station No. 3 (at index 3), you can get 4 liters of petrol. At this time, the fuel tank has = 0 + 4 = 4 liters of gasoline 
. Go to gas station No. 4. At this time, the fuel tank has 4 - 1 + 5 = 8 liters of gasoline. 
Go to No. 0 gas station, and the fuel tank has 8 - 2 + 1 = 7 liters of gasoline Go 
to No. 1 gas station, at this time the fuel tank has 7 - 3 + 2 = 6 liters of gasoline 
Go to No. 2 gas station, at this time the fuel tank has 6 - 4 + 3 = 5 liters of gasoline 
Go to No. 3 gas station, you It takes 5 liters of petrol, just enough to get you back to gas station #3. 
Therefore, 3 can be the starting index.

train of thought

At first, I thought of simulating one by one, but this method is not easy to implement. After all, you have to run around in circles, and it is very troublesome to calculate and do, so the brute force solution can be written, but it is difficult .

There is a very clever method for this question, which is to think about how to complete a lap? Only when the total amount of fuel in the car is more than the total amount of fuel required to complete a lap or just enough to complete a lap. If you think about it this way, this question will be much simpler. We only need to add up the remaining fuel at each gas station, find where the fuel is negative, and just start running from the next gas station. The process is shown in the figure:

The interval sum of [0, 2] is negative, so you need to start running from subscript 3, because no matter how you run before, as long as you reach subscript 2, you will run out of gas, so you need to start running from the next gas station, so that you can Complete a lap.

Code

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int curSum = 0;
        int totalSum = 0;
        int start = 0;
        for(int i = 0;i < gas.size();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;

    }
};

leetcode 135. Distribute candy

Topic link: 135. Distributing candies - LeetCode

Video link: Greedy algorithm, it is easy to lose sight of the other by taking both! LeetCode: 135. Distributing candies_哔哩哔哩_bilibili

topic overview

n children stand in a row. You are given an array of integers  ratings representing each child's rating.

You need to distribute candy to these children according to the following requirements:

  • Each child is assigned at least  1 one candy.
  • The child with the higher score of two adjacent children gets more candies.

Please distribute candies to each child, calculate and return  the minimum number of candies that need to be prepared  .

Example 1:

Input: ratings = [1,0,2]
 Output: 5
 Explanation: You can distribute 2, 1, and 2 candies to the first, second, and third children, respectively.

train of thought

This question cannot be attacked on the left and right sides at the same time. As the saying goes, you can’t have both. If you compare the left side with the same child and then compare the right side, you will lose sight of the other, so this question should be done on one side.

Take the array [1,2,2,5,4,3,2] as an example:

First of all, first determine the situation where the score of the child on the right is higher than that of the child on the left, that is to say, traverse from front to back .

Every child must have at least one candy no matter how much the score is, so the leftmost child must have a candy. If the child on the right has a higher score than the child on the left, then +1 is performed on the basis that the child on the left has a candy. If there is no child on the left If the child scores high, then it is still a candy.

135. Handing out candy

Then, determine the situation that the score of the child on the left is higher than that of the child on the right , that is to say, traverse from the back to the front .

135. Handing out candies 1

 Why do we have to traverse from the back to the front? Because if you traverse from front to back, the situation shown in the following figure will appear:

 Manually simulate this process by yourself, and you will clearly find out where the problem lies.

Code

class Solution {
public:
    int candy(vector<int>& ratings) {
        vector<int> candyVec(ratings.size(),1);
        for(int i = 1;i < ratings.size();i++) {
            if(ratings[i] > ratings[i - 1]) {
                candyVec[i] = candyVec[i - 1] + 1;
            }
        }
        for(int i = ratings.size() - 2;i >= 0;i--) {
            if(ratings[i] > ratings[i + 1]) {
                candyVec[i] = max(candyVec[i],candyVec[i + 1] + 1);
            }
        }
        int result = 0;
        for(int i = 0;i < candyVec.size();i++) result += candyVec[i];
        return result;

    }
};

Guess you like

Origin blog.csdn.net/m0_74583479/article/details/132244743