VOOZH about

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

⇱ CSES Solutions - Towers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Towers

Last Updated : 23 Jul, 2025

You are given n cubes as an array cubes[] in a certain order and contains only distinct elements. Your task is to build towers using them. Whenever two cubes are one on top of the other, the upper cube must be smaller than the lower cube. You must process the cubes in the given order. You can always either place the cube on top of an existing tower or begin a new tower. What is the minimum possible number of towers?

Examples:

Input: n = 5, cubes[] = {3, 8, 2, 1, 5}
Output: 2
Explanation: We can make 2 towers {3, 2, 1} and {8, 5}.

Input: n = 4, cubes[] = {4, 3, 1, 2}
Output: 2
Explanation: We can make 2 towers {4, 3, 1} and {2}.

Input: n = 4, cubes[] = {2,2,1,1}
Output: 2
Explanation: We can make 2 towers {2,1} and {2,1}.

Approach: To solve the problem, follow the below idea:

We can solve the problem by iterating over the cubes and for every cube, we will find the smallest cube which is larger than the current cube and is placed on the top of any tower. This can be done by storing only the top elements of the tower in a multiset. So, for every block we find the tower that has the topmost block just greater than the current block. This can be easily found using Binary Search upper bound on multiset. Also, whenever we add a block to a tower, we need to update the top of the tower as well.

Step-by-step algorithm:

  • Maintain a variable, say ans to store the number of towers needed.
  • Maintain a multiset, say topElements store the topmost cubes of all towers.
  • For each cube with size cubes[i], find the smallest cube which has size > cubes[i] and is among the top-most cubes of towers.
    • If there is no cube among the top-most cubes which has size > cubes[i], then we have to make another tower.
    • Otherwise, if there is a cube among the top-most cubes which has size > cubes[i], then we place the current cube on top of it.
  • After all the iterations, return ans as the final answer.

Below is the implementation of the algorithm:


Output
2

Time Complexity: O(N * logN), where N is the number of cubes.
Auxiliary Space: O(N)

Comment
Article Tags:
Article Tags: