Minimize Maximum Component Cost Problem
Description
LeetCode Problem 3613.
You are given an undirected connected graph with n nodes labeled from 0 to n - 1 and a 2D integer array edges where edges[i] = [u_i, v_i, w_i] denotes an undirected edge between node u_i and node v_i with weight w_i, and an integer k.
You are allowed to remove any number of edges from the graph such that the resulting graph has at most k connected components.
The cost of a component is defined as the maximum edge weight in that component. If a component has no edges, its cost is 0.
Return the minimum possible value of the maximum cost among all components after such removals.
Example 1:
Input: n = 5, edges = [[0,1,4],[1,2,3],[1,3,2],[3,4,6]], k = 2
Output: 4
Explanation:

- Remove the edge between nodes 3 and 4 (weight 6).
- The resulting components have costs of 0 and 4, so the overall maximum cost is 4.
Example 2:
Input: n = 4, edges = [[0,1,5],[1,2,5],[2,3,5]], k = 1
Output: 5
Explanation:

- No edge can be removed, since allowing only one component (k = 1) requires the graph to stay fully connected.
- That single component’s cost equals its largest edge weight, which is 5.
Constraints:
1 <= n <= 5 * 10^40 <= edges.length <= 10^5edges[i].length == 30 <= u_i, v_i < n1 <= w_i <= 10^61 <= k <= n- The input graph is connected.
Solution
Approach: Sorting + Union-Find
If k = n, every edge can be removed and each node is its own component, so the cost is 0.
Otherwise, think of Kruskal's algorithm. Sort the edges by weight and add them one at a time with a union-find, starting from n separate nodes. Each edge that joins two different components reduces the component count by one. The first time the count drops to k or below, the edges added so far are enough, and every heavier edge can be removed. The weight of that last edge is the largest weight we still keep, so it is the answer.
Complexity: O(m log m) time and O(n) space, where m is the number of edges.
class Solution:
def minCost(self, n: int, edges: List[List[int]], k: int) -> int:
def find(x: int) -> int:
if p[x] != x:
p[x] = find(p[x])
return p[x]
if k == n:
return 0
edges.sort(key=lambda x: x[2])
cnt = n
p = list(range(n))
for u, v, w in edges:
pu, pv = find(u), find(v)
if pu != pv:
p[pu] = pv
cnt -= 1
if cnt <= k:
return w
return 0