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.
Input: blocks =[1], split =1Output: 1Explanation: We use 1 worker to build 1 block in1 time unit.
Example 2:
1
2
3
Input: blocks =[1,2], split =5Output: 7Explanation: We split the worker into 2 workers in5 time units then assign each of them to a block so the cost is5+ max(1,2)=7.
Example 3:
1
2
3
4
5
Input: blocks =[1,2,3], split =1Output: 4Explanation: 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 is1+ max(3,1+ max(1,2))=4.
To minimize the total time, we want to split workers only when it helps parallelize block building. By always combining the two smallest build times (using a min-heap), we ensure that splits are used efficiently, and the largest blocks are built last, minimizing the overall time.
classSolution {
publicintminBuildTime(int[] blocks, int split) {
PriorityQueue<Integer> pq =new PriorityQueue<>();
for (int b : blocks) pq.add(b);
while (pq.size() > 1) {
int a = pq.poll(), b = pq.poll();
pq.add(split + Math.max(a, b));
}
return pq.peek();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funminBuildTime(blocks: IntArray, split: Int): Int {
val pq = PriorityQueue<Int>()
blocks.forEach { pq.add(it) }
while (pq.size > 1) {
val a = pq.poll()
val b = pq.poll()
pq.add(split + maxOf(a, b))
}
return pq.peek()
}
}
1
2
3
4
5
6
7
8
9
10
import heapq
classSolution:
defminBuildTime(self, blocks: list[int], split: int) -> int:
h = blocks[:]
heapq.heapify(h)
while len(h) >1:
a = heapq.heappop(h)
b = heapq.heappop(h)
heapq.heappush(h, split + max(a, b))
return h[0]
1
2
3
4
5
6
7
8
9
10
11
12
13
use std::collections::BinaryHeap;
impl Solution {
pubfnmin_build_time(blocks: Vec<i32>, split: i32) -> i32 {
letmut heap = std::collections::BinaryHeap::new();
for b in blocks { heap.push(-b); }
while heap.len() >1 {
let a =-heap.pop().unwrap();
let b =-heap.pop().unwrap();
heap.push(-(split + a.max(b)));
}
-heap.pop().unwrap()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
minBuildTime(blocks: number[], split: number):number {
consth= [...blocks].sort((a, b) =>a-b);
while (h.length>1) {
consta=h.shift()!;
constb=h.shift()!;
h.push(split+ Math.max(a, b));
h.sort((a, b) =>a-b);
}
returnh[0];
}
}