Minimum Time to Build Blocks in C++

C++Server Side ProgrammingProgramming

Suppose we have a list of blocks, if we have blocks[i] = t, this means that the i-th block needs t units of time to be built. A block can only be built by exactly one worker. Single worker can either split into two workers or build a block then go home. These two decisions take some time. The time cost of spliting one worker into two workers is given as a number called split.

So, if the input is like blocks = [1,2], and split = 5, then the output will be 7 as we can split the worker into 2 workers in 5 time units then assign each of them to a block so the cost is 5 + maximum of 1 and 2 = 7.

To solve this, we will follow these steps −

  • define one priority queue pq

  • for initialize i := 0, when i < size of blocks, update (increase i by 1), do −

    • insert blocks[i] into pq

  • while size of pq > 1, do −

    • delete element from pq

    • x := top element of pq

    • delete element from pq

    • insert split + x into pq

  • return top element of pq

Let us see the following implementation to get better understanding −


 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   int minBuildTime(vector<int>& blocks, int split) {
      priority_queue<int, vector<int>, greater<int> > pq;
      for (int i = 0; i < blocks.size(); i++)
      while (pq.size() > 1) {
         int x =;
         pq.push(split + x);
   Solution ob;
   vector<int> v = {1,2};
   cout << (ob.minBuildTime(v, 5));


{1,2}, 5


Published on 11-Jul-2020 12:37:27