![]() |
VOOZH | about |
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:
Below is the implementation of the algorithm:
2
Time Complexity: O(N * logN), where N is the number of cubes.
Auxiliary Space: O(N)