You are managing a project that is about building the blocks. You need ‘workers’ to build the ‘blocks’, and a block can only be built by exactly one worker (means once a worker assigned to a particular block he needs to finish it). A worker can either split into two workers or build a block then go home. There is an extra time cost associated with both of the operations.
You are given an array ‘BLOCK’ where ‘BLOCK[i]’ denotes the time required to build the ith block. You are also given an integer, ‘SPLIT’, which denotes the time required to split the worker. The process starts with only one worker. Your task is to find the “minimum time” required to build all the blocks.
Note:Two or more workers may split simultaneously so that the cost would be ‘SPLIT’ at that time.
The first line contains an integer ‘T’, which denotes the number of test cases to be run. Then, the T test cases follow.
The first line of each test case contains two positive integers, ‘N’, and ‘SPLIT’, denote the total number of blocks and the time required to split a worker.
The second line of each test case contains ‘N’ positive integers, where ith integer represents the time required to build the ith block.
Output Format:
For each test case, print the “minimum time” required to build all the blocks.
Output for each test case will be printed in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= ‘T’ <= 10
1 <= ‘N’ <= 10^4
1 <= ‘SPLIT’ <= 100
1 <= ‘BLOCK[i]’ <= 10^4
Time Limit: 1sec
1
1 3
4
4
We don’t need to perform any split. We can directly use one worker to build one block in 4 units of time.
1
2 3
1 2
5
Try to use the concept of Huffman coding.
Let us try to visualize this by using an example, ‘BLOCK’ = [1, 2, 4, 5] , ‘SPLIT’ = 4.
Step 1: Min-heap at this step = [1, 2, 4, 5].
Step 2: Min-heap at this step = [ 4, 5, 6].
Step 3: Min-heap at this step = [6, 9].
Step 4: Min-heap at this step = [13], i,e., the size is ‘1’ so we return the top element.
So, the total cost to build all blocks would be ‘13’.
O(N * logN), where ‘N’ is the number blocks.
We are using the priority queue that takes O(logN) time to perform operations like push and pop. We are performing these operations ‘N’ times. So, the time complexity will be O(N * logN).
O(N), where ‘N’ is the number blocks.
As we are using a priority queue that can have at max ‘N’ elements at a time. Hence, the space complexity will be O(N).