Problem Link: Minimum Lift Trips
Problem Statement:
There are N people waiting at the ground floor to go to the top floor in a small lift. The lift can carry at most two people at once, and there is a weight limit of x for the lift. Each person has a specific weight, and the sum of the weights of the people in the lift cannot exceed x.
Your task is to determine the minimum number of trips the lift needs to make to get all the people to the top floor
Approach:
The key idea in this problem is to efficiently pair the lightest and heaviest people together in order to minimize the number of trips.
-
Sorting the Weights: First, we sort the
weightsarray in ascending order. This helps us quickly identify which people can share a trip based on the weight limitx. -
Two Pointers Technique: We use two pointers: one (
i) starts at the beginning of the sorted array (lightest person), and the other (j) starts at the end of the array (heaviest person). -
Checking for Pairing:
-
If the sum of the weights of the person at index
i(lightest) and the person at indexj(heaviest) is less than or equal tox, they can share a trip. We incrementito move to the next lightest person and decrementjto move to the next heaviest person. -
If the sum exceeds
x, the person at indexj(heaviest) goes alone, and we only decrementj.
-
-
Counting Trips: Each time we transport one or two people, we count it as a trip. We continue this process until all people are transported.
-
Result: The variable
tripsholds the total number of trips required, which is then printed at the end.
This approach efficiently pairs people to minimize trips by always attempting to combine the heaviest and lightest individuals first, ensuring that the total weight stays under the limit.
Time Complexity:
- Sorting the weights takes O(N log N), where
Nis the number of people. - The two-pointer traversal runs in O(N) since both pointers traverse the list once.
Thus, the total time complexity is O(N log N).
Space Complexity:
The space complexity is O(N) because we store the weights of N people in a vector.