Minimum Time to Build Blocks Problem
Description
LeetCode Problem 1199.
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 spliting 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.
Example 1:
Input: blocks = [1], split = 1
Output: 1
Explanation: We use 1 worker to build 1 block in 1 time unit.
Example 2:
Input: blocks = [1,2], split = 5
Output: 7
Explanation: We split the worker into 2 workers in 5 time units then assign each of them to a block so the cost is 5 + max(1, 2) = 7.
Example 3:
Input: blocks = [1,2,3], split = 1
Output: 4
Explanation: Split 1 worker into 2, then assign the first worker to the last block and split the second worker into 2.
Then, use the two unassigned workers to build the first two blocks.
The cost is 1 + max(3, 1 + max(1, 2)) = 4.
Constraints:
1 <= blocks.length <= 10001 <= blocks[i] <= 10^51 <= split <= 100
Solution
Approach: Greedy Merging with a Min-Heap
Deciding forwards how the workers should split is hard. It is easier to run the process backwards. Think of the final schedule as a binary tree: each split is an inner node that costs split and starts two independent sub-schedules, and each block is a leaf. Two sub-schedules that take a and b time can be joined by one split into a schedule that takes split + max(a, b).
So the question becomes: repeatedly merge two blocks into one of time split + max(a, b) until one block is left; what is the smallest possible final time?
This is like building a Huffman tree. Greedily merge the two quickest blocks each time. The slowest blocks should sit as close to the root as possible, so that they wait for as few splits as possible, and merging the two smallest first pushes them deepest. Merging the two smallest a <= b gives split + b.
Keep the times in a min-heap: pop the two smallest, push split + (the larger one), and repeat until one value remains. That value is the answer. With one block there is no split at all, and the answer is the block's own time.
Complexity: O(n log n) time and O(n) space for the heap.
import heapq
class Solution:
def minBuildTime(self, blocks: List[int], split: int) -> int:
heap = list(blocks)
heapq.heapify(heap)
while len(heap) > 1:
# Merge the two quickest blocks: one worker splits, then each half builds one of them.
heapq.heappop(heap) # the smaller one finishes no later than the other
second = heapq.heappop(heap)
heapq.heappush(heap, second + split)
return heap[0]