Skip to content

1199. Minimum Time to Build Blocks 👍

  • Time: $O(n\log n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int minBuildTime(vector<int>& blocks, int split) {
    priority_queue<int, vector<int>, greater<>> minHeap;

    for (const int block : blocks)
      minHeap.push(block);

    while (minHeap.size() > 1) {
      minHeap.pop();                // the minimum
      const int x = minHeap.top();  // the second minimum
      minHeap.pop();
      minHeap.push(x + split);
    }

    return minHeap.top();
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int minBuildTime(int[] blocks, int split) {
    Queue<Integer> minHeap = new PriorityQueue<>();

    for (final int block : blocks)
      minHeap.offer(block);

    while (minHeap.size() > 1) {
      minHeap.poll();               // the minimum
      final int x = minHeap.poll(); // the second minimum
      minHeap.offer(x + split);
    }

    return minHeap.poll();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def minBuildTime(self, blocks: list[int], split: int) -> int:
    minHeap = blocks.copy()
    heapify(minHeap)

    while len(minHeap) > 1:
      heapq.heappop(minHeap)  # the minimum
      x = heapq.heappop(minHeap)  # the second minimum
      heapq.heappush(minHeap, x + split)

    return minHeap[0]