![]() |
VOOZH | about |
Given an array people[] where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry at most two people at a time with total maximum weight of W. Return the minimum number of boats to carry all the people.
Examples:
Input: people = [1, 2], W = 3
Output: 1
Explanation: All the people can sit in the same boat.Input: people = [3, 2, 2, 1], W = 3
Output: 3
Explanation: First person will sit in first boat; the second person will sit in the second boat and the third and fourth person will sit in the third boat.
Approach: To solve the problem, follow the below idea:
The problem can be solved using Two-Pointers technique. Sort the weights in ascending order and use two pointers, left and right. The left points to the lightest person to be seated and the right points to the heaviest person to be seated. Since at max only two persons can sit in one boat, check if the left and the right person can sit in the same boat.
- If both the persons can sit in the same boat, then increment left and decrement right. Also increase the count of boats.
- Otherwise, make the heavier person sit in the boat and decrement right. Also, increase the count of boats.
Repeat the above till left and right don't cross each other. Finally, print the count of boats.
Step-by-step algorithm:
Below is the implementation of the above approach:
3
Time Complexity: O(N * logN), where N is the number of people.
Space Complexity: O(1)