![]() |
VOOZH | about |
There are N children who want to go to a Ferris wheel in the form of array arr[], and your task is to find a gondola for each child. Each gondola may have one or two children in it, and in addition, the total weight in a gondola may not exceed X. You know the weight of every child. What is the minimum number of gondolas needed for the children?
Input: N = 4, X = 10, arr[] = {7, 2, 3, 9}
Output: 3
Explanation: We need only 3 gondolas: {2, 3}, {7} and {9}.Input: N = 4, X = 6, arr[] = {2, 3, 3, 4}
Output: 2
Explanation: We need only 2 gondolas: {2, 4} and {3, 3}
Approach: To solve the problem, follow the below idea:
We can solve the problem using a Greedy Approach. In order to have the minimum number of gondolas, we can start from the child with the largest weight and pair it with the child with the smallest weight. If the total weight of both the children does not exceed x, then we can fit both the children and start the pairing of child with second largest weight with child with the second smallest weight, and so on. If at any point, the sum of both the children exceeds x, then it means that the heavier child has to go alone and then keep on searching for pairs of students to pair.
Step-by-step algorithm:
Below is the implementation of the algorithm:
3
Time Complexity: O(NlogN), where N is the total number of children.
Auxiliary Space: O(1)