DSAPROB29 - Editorial

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.

  1. Sorting the Weights: First, we sort the weights array in ascending order. This helps us quickly identify which people can share a trip based on the weight limit x.

  2. 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).

  3. Checking for Pairing:

    • If the sum of the weights of the person at index i (lightest) and the person at index j (heaviest) is less than or equal to x, they can share a trip. We increment i to move to the next lightest person and decrement j to move to the next heaviest person.

    • If the sum exceeds x, the person at index j (heaviest) goes alone, and we only decrement j.

  4. 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.

  5. Result: The variable trips holds 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 N is 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.