Day31|leetcode 455. Distributing Cookies, 376. Swing Sequence, 53. Maximum Subsequence Sum

Start the greedy algorithm today. There are no routines and rules to follow in the greedy algorithm, as long as the local optimum leads to the global optimum.

There is no connection between greed and greed, one question and one pattern, greed is a broom.

The greedy algorithm is either very simple, so simple that you will doubt whether it is greedy, or it is so difficult that you doubt life, so don't underestimate the greedy algorithm.

leetcode 455. Distribute cookies

Topic Link: 455. Distributing Cookies - LeetCode

Video link: Greedy algorithm, which child do you want to feed first? | LeetCode: 455. Distribute cookies_哔哩哔哩_bilibili


topic overview

Let's say you're a great parent and want to give your kids some cookies. However, each child is given no more than one cookie.

For each child  i, there is an appetite value  g[i], which is the smallest size of biscuit that can satisfy the child's appetite; and each biscuit  jhas a size  s[j] . If  s[j] >= g[i], we can  j distribute this cookie to a child  i , the child will be satisfied. Your goal is to satisfy as many children as possible and output this maximum value.

Example 1:

Input: g = [1,2,3], s = [1,1]
 Output: 1
 Explanation:  
You have three children and two biscuits, and the appetite values ​​of the three children are: 1,2,3. 
Although you have two small biscuits, since they both have a size of 1, you can only satisfy a child with an appetite value of 1. 
So you should output 1.

train of thought

Until then, kid appetites and cookies need to be sorted!

There are two approaches to this question

The first method (small biscuits to satisfy small appetites): At the beginning, I thought of this method. First, use small biscuits to satisfy children with small appetites. The process is shown in the figure:

 First use biscuit 1 to satisfy child 1 with a small appetite, then biscuit 3 to satisfy child 2, biscuit 5 cannot satisfy child 7, so biscuit is moved to biscuit 9 after biscuit 9, and biscuit 9 can satisfy child 7.

The local optimum here is to feed small biscuits to children with small appetites, which will not cause waste, and the global optimum is to feed as many children as possible.

Code implementation (method 1)

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(),g.end());
        sort(s.begin(),s.end());
        int index = 0;
        for(int i = 0;i < s.size();i++) {
            if(index < g.size() && g[index] <= s[i]) {
                index++;
            }
        }
        return index;

    }
};

The second type (big biscuits satisfy a big appetite):

If the largest biscuit satisfies the child with the largest appetite, it must also satisfy the child with the smallest appetite, but it would be wasteful to satisfy the small appetite with a large biscuit, so satisfy the older child with a large biscuit.

The local optimum here is to feed the children with big appetites with big biscuits, which will not cause waste, and the global optimum is to feed as many children as possible.

Code implementation (method 2)

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(), g.end());
        sort(s.begin(), s.end());
        int index = s.size() - 1; // 饼干数组的下标
        int result = 0;
        for (int i = g.size() - 1; i >= 0; i--) { // 遍历胃口
            if (index >= 0 && s[index] >= g[i]) { // 遍历饼干
                result++;
                index--;
            }
        }
        return result;
    }
};

Leetcode 376. Wiggle Sequence

Topic link: 376. Swing sequence - LeetCode

Video link: Greedy Algorithm, looking for swings with details! | LeetCode: 376. Swing sequence_哔哩哔哩_bilibili

topic overview

A sequence of numbers is called a oscillating sequence if the difference between consecutive numbers strictly alternates between positive and negative  . The first difference (if any) may be positive or negative. Sequences with only one element or with two unequal elements are also considered swing sequences.

  • For example,  [1, 7, 4, 9, 2, 5] a  wobble sequence  , since the difference  (6, -3, 5, -7, 3) is alternately positive and negative.

  • Conversely, the sum is [1, 4, 7, 2, 5] not  [1, 7, 4, 5, 5] a wobble sequence, the first sequence because its first two differences are positive, and the second sequence because its last difference is zero.

A subsequence  can be obtained by deleting some (or none) elements from the original sequence, leaving the remaining elements in their original order.

Given an array of integers  nums , return  the length of the longest subsequencenums  in  the wobble  sequence   .

Example 1:

Input: nums = [1,7,4,9,2,5]
 Output: 6
 Explanation: The entire sequence is a swing sequence, and the difference between each element is (6, -3, 5, -7, 3)

Example 2:

Input: nums = [1,17,5,10,13,15,10,5,16,8]
 Output: 7
 Explanation: This sequence contains several wobble sequences of length 7. 
One of them is [1, 17, 10, 13, 10, 16, 8] and the difference between the elements is (16, -7, 3, -3, 6, -8) .

train of thought

Take Example 2 as an example, its operation process is shown in the figure:

376. Wobble Sequence

 In actual operation, there is no need to delete these points, just count the number of peaks.

Three situations need to be considered in this question:

1. There is a flat slope in the middle of the uphill and downhill

Take [1, 2, 2, 2, 1] as an example, its swing sequence length is 3, either delete the three 2s on the left, or delete the three 2s on the right.

 

2. There is a head and a tail

If there are two elements in the array, it is impossible to calculate according to the previous idea, because at least three elements are needed to calculate, so in this case, it is assumed that there is a number in front of the number at the beginning of the array. This number is the same as The first number at the beginning of the array is the same, and there is a peak at the end by default, so that the above rules can continue to run.

You can also take this situation as a separate situation, just judge that there are only two elements in the array, and if they are not the same, just return two directly.

3. Monotonous slopes have flat slopes (the most easily overlooked situation)

The length of this swing sequence is 2. If you think about it according to the previous idea, the length of its swing sequence is 3, because prediff is also recorded in 2, but it is not the largest peak value, so it is wrong, so we have to Only update the prediff when there is a swing change in the slope.

 

Code

class Solution {
public:
    int wiggleMaxLength(vector<int>& nums) {
        if(nums.size() <= 1) return nums.size();
        int curDiff = 0;
        int preDiff = 0;
        int result = 1;
        for(int i = 0;i < nums.size() - 1;i++) {
            curDiff = nums[i + 1] - nums[i];
            if((preDiff >= 0 && curDiff < 0) || (preDiff <= 0 && curDiff >0)) {
                result++;
                preDiff = curDiff;
            }
        }
        return result;

    }
};

leetcode 53. Maximum Subsequence Sum

Topic Link: 53. Maximum Subarray Sum - LeetCode

Video link: The ingenuity of the greedy algorithm needs to be realized slowly! LeetCode: 53. Maximum Subsequence Sum_哔哩哔哩_bilibili

 

topic overview

Given an array of integers  nums , please find a continuous subarray with the maximum sum (the subarray contains at least one element), and return its maximum sum.

A subarray  is a contiguous part of an array.

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
 Output: 6
 Explanation: The sum of consecutive subarrays [4,-1,2,1] is the largest, which is 6

train of thought

Greedy in this question is that when the continuous sum is negative , it will start to accumulate again from the next element, because after all, negative numbers will make the sum smaller and smaller, so it should be broken to avoid chaos. If the continuous sum is a positive number, it will continue to be reserved, because no matter whether the sum is large or small, it will have an increasing effect on the back. Of course, there must be a variable that is continuously updating the maximum value.

If it is broken, it must be a continuous sum that is negative , not a negative number . There is a big difference between the two.

Code

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int result = INT32_MIN;
        int count = 0;
        for(int i = 0;i < nums.size();i++) {
            count += nums[i];
            if(count > result) {
                result = count;
            }
            if(count <= 0) count = 0;
        }
        return result;

    }
};

Guess you like

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