VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-ferris-wheel/

⇱ CSES Solutions - Ferris Wheel - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Ferris Wheel

Last Updated : 23 Jul, 2025

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:

  • Sort the array arr[] in ascending order.
  • Initialize 2 pointers l and h to keep track of lightest and heaviest child.
  • If the heaviest and the lightest child can pair with each other, then pair them up and increase l by 1, decrease r by 1 and increment ans.
  • Otherwise, if the heaviest and the lightest child cannot pair, then the heaviest child will only sit in one gondola and decrease r by 1 and increment ans.
  • Return the final ans after iterating over all the children.

Below is the implementation of the algorithm:


Output
3

Time Complexity: O(NlogN), where N is the total number of children.
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: