#3613
Minimize Maximum Component Cost
MediumBinary SearchUnion-FindGraph TheorySortingBinary SearchUnion-Find
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(E log E + E α(N)) |
| Space | O(1) | O(N) |
💡
Intuition
Time O(E log E + E α(N))Space O(N)
Use binary search on the maximum edge weight and a union-find structure to efficiently count components.
⚙️
Algorithm
3 steps- 1Step 1: Sort edges by weight.
- 2Step 2: Perform binary search on the edge weights, checking if we can form at most k components with edges <= mid.
- 3Step 3: Use union-find to track connected components during the check.
solution.py24 lines
1def minMaxCost(n, edges, k):
2 edges.sort(key=lambda x: x[2])
3 def canFormComponents(maxWeight):
4 parent = list(range(n))
5 def find(x):
6 if parent[x] != x:
7 parent[x] = find(parent[x])
8 return parent[x]
9 count = n
10 for u, v, w in edges:
11 if w <= maxWeight:
12 rootU, rootV = find(u), find(v)
13 if rootU != rootV:
14 parent[rootU] = rootV
15 count -= 1
16 return count <= k
17 low, high = 0, edges[-1][2]
18 while low < high:
19 mid = (low + high) // 2
20 if canFormComponents(mid):
21 high = mid
22 else:
23 low = mid + 1
24 return lowℹ
Complexity note: Sorting edges takes O(E log E), and union-find operations are nearly constant time due to path compression.
- 1Binary search helps narrow down the maximum cost efficiently.
- 2Union-Find allows quick component counting.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.