Minimum Time to Build Blocks - Problem

You are given a list of blocks, where blocks[i] = t means that the i-th block needs t units of time to be built. A block can only be built by exactly one worker.

A worker can either split into two workers (number of workers increases by one) or build a block then go home. Both decisions cost some time.

The time cost of splitting one worker into two workers is given as an integer split. Note that if two workers split at the same time, they split in parallel so the cost would be split.

Output the minimum time needed to build all blocks. Initially, there is only one worker.

Input & Output

Example 1 — Basic Case
$ Input: blocks = [1], split = 1
Output: 1
💡 Note: Only one block to build, so the minimum time is just the time to build that block: 1
Example 2 — Two Blocks
$ Input: blocks = [1,2], split = 5
Output: 7
💡 Note: We can either build sequentially (1+2=3) or split then build in parallel (5+max(1,2)=7). However, the optimal solution using the greedy approach merges the blocks: split cost + max(1,2) = 5+2 = 7.
Example 3 — Split is Beneficial
$ Input: blocks = [1,1,1], split = 1
Output: 3
💡 Note: Split twice to get 4 workers (cost 2), then build all blocks in parallel (cost 1), total = 2+1 = 3. This is better than sequential building (cost 3).

Constraints

  • 1 ≤ blocks.length ≤ 1000
  • 1 ≤ blocks[i] ≤ 104
  • 1 ≤ split ≤ 100

Visualization

Tap to expand
Minimum Time to Build Blocks Greedy with Priority Queue Approach INPUT blocks array: 1 index: 0 split cost: 1 Initial Workers: 1 worker blocks=[1], split=1 ALGORITHM STEPS 1 Sort Descending blocks: [1] (already sorted) 2 Init Min-Heap Push all blocks to heap 1 heap: [1] 3 Check Heap Size size=1, no split needed 4 Build Block Worker builds block[0] Time = max(heap) = 1 1 worker builds 1 block in 1 unit No splitting required! FINAL RESULT Timeline: t=0 Start t=1 Done Worker builds block[0] Minimum Time 1 OK - Output: 1 Single block needs single worker, no split Key Insight: Use a min-heap to greedily combine the two smallest build times. When heap size is 1, that's the answer. For multiple blocks: pop two smallest, combine as split + max(a,b), push back. Repeat until one element remains. TutorialsPoint - Minimum Time to Build Blocks | Greedy with Priority Queue
Asked in
Google 15 Microsoft 12
31.5K Views
Medium Frequency
~30 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen