Huawei OD interview hand tearing code real questions [Lifeboat]

Given an array people . people[i] represents the weight of the i-th person, the number of boats is not limited, and the maximum weight that each boat can carry is limit. Each boat can carry up to two people at the same time, but the condition is that the sum of the weights of these people is at most the limit.

Returns the minimum number of ships required to carry all of the .

        This question is almost the same as the previous computer test question: Rent a car and ride on Green Island. If you are interested, you can search my blog to see.

        The question is still that the interviewer will give a leetcode question number, and then let you go directly to leetcode to do the question, submit it, and see the pass rate. This question is relatively simple, but pay attention to reading the question. The subject pays great attention to details. When reading the questions, pause for three seconds to think after each sentence. The key to this question is [Each ship can carry up to two people at the same time, but the condition is that the sum of the weights of these people is at most limit]

To minimize the number of boats needed, there should be as many boats carrying two people as possible.

Greedy algorithm process:

Let the length of people be n. Consider the lightest person:

If he cannot take the same boat with the heaviest person, then the heaviest person cannot take the same boat with anyone, and the heaviest person should be assigned a separate boat. After removing the heaviest person from people, we reduce the size of the problem to the minimum number of boats required to solve the remaining n−1 people, adding one to the answer to the original problem.
If he can take the same boat with the heaviest person, then he can take the same boat with anyone else. In order to use the boat's carrying weight as much as possible, he chooses to take the same boat with the heaviest person is optimal. After removing the lightest and heaviest people from people, we reduce the size of the problem to the minimum number of boats needed to solve the remaining n−2 people, adding one to the answer to the original problem.
When implementing the code, I

Guess you like

Origin blog.csdn.net/misayaaaaa/article/details/131161585