Minimize Maximum Component Cost

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] = [ui, vi, wi] denotes an undirected edge between node ui and node vi with weight wi, 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
Inputn = 5, edges = [[0,1,4],[1,2,3],[1,3,2],[3,4,6]], k = 2
Output4
Removing the edge between nodes 3 and 4 with weight 6 leaves components with costs 0 and 4, so the maximum cost is 4.
Example 2
Inputn = 4, edges = [[0,1,5],[1,2,5],[2,3,5]], k = 1
Output5
With k = 1, the graph must remain connected, so the single component's cost is its largest edge weight, 5.

Constraints

  • 1 <= n <= 5 * 10^4
  • 0 <= edges.length <= 10^5
  • edges[i].length == 3
  • 0 <= ui, vi < n
  • 1 <= wi <= 10^6
  • 1 <= k <= n
  • The input graph is connected.

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate