Given an undirected graph **G** with **N** nodes, **M** edges, and an integer **K**, the task is to find the maximum count of edges that can be removed such that there remains exactly **K** connected components after the removal of edges. If the graph cannot contain **K **connect components, print **-1**.

**Examples:**

Input:N = 4, M = 3, K = 2, Edges[][] = {{1, 2}, {2, 3}, {3, 4}}

Output:1Explanation:

One possible way is to remove edge [1, 2]. Then there will be 2 connect components as shown below:

Input:N = 3, M = 3, K = 3, Edges[][] = {{1, 2}, {2, 3}, {3, 1}}

Output:3Explanation:All edges can be removed to make 3 connected components as shown below:

**Approach:** To solve the given problem, count the number of connected components present in the given graph. Let the count be **C**. Observe that if **C** is greater than **K** then no possible edge removal can generate **K** connected components as the number of connected components will only increase. Otherwise, the answer will always exist.

Following observations need to be made in order to solve the problem:

- Suppose C
_{1}, C_{2}, …, C_{c}, are the number of node in each connected component. Then, each component must have edges as C_{1 }– 1, C_{2 }– 1, …, C_{c }-1 after edges are removed. Therefore,

**C**, where_{1}– 1 + C_{2}– 1 + … + C_{c}– 1 = C_{1}+ C_{2}+ … + C_{c}– C = N – C**N**is the number of nodes. - The above condition will give us the
**C**connected components by removing**M – (N – C)**edges as**N – C**edges are needed to make**C**components. To get**K**components,**(K – C)**more edges must be removed. - Hence, the total count of edges to be removed is given by:

**M – (N – C) + (K – C) = M – N + K**

Follow the steps below to solve the problem:

- Count the number of connected components present in the given graph. Let the count be
**C**. - If
**C**is greater than**K**, print**-1**. - Else print
**M – N + K**where**N**is the number f nodes,**M**is the number of edges and**K**is the required number of connected components.

Below is the implementation of the above approach:

## Python3

`# Python program for the above approach ` ` ` `class` `Graph: ` ` ` ` ` `# Constructor ` ` ` `def` `__init__(` `self` `, V): ` ` ` ` ` `# No. of vertices ` ` ` `self` `.V ` `=` `V ` ` ` ` ` `# Dictionary of lists ` ` ` `self` `.adj ` `=` `{i: [] ` `for` `i ` `in` `range` `(` `1` `, V ` `+` `1` `)} ` ` ` ` ` `# Function to add edge ` ` ` `# in the graph ` ` ` `def` `addEdge(` `self` `, v, w): ` ` ` `self` `.adj[v].append(w) ` ` ` `self` `.adj[w].append(v) ` ` ` ` ` `# Function to perform DFS ` ` ` `def` `DFS(` `self` `, s, visited): ` ` ` ` ` `# Create a stack for DFS ` ` ` `stack ` `=` `[] ` ` ` ` ` `# Push the current source node ` ` ` `stack.append(s) ` ` ` `while` `(` `len` `(stack)): ` ` ` ` ` `# Pop a vertex from stack ` ` ` `# and print it ` ` ` `s ` `=` `stack[` `-` `1` `] ` ` ` `stack.pop() ` ` ` ` ` `# Traverse adjacent vertices ` ` ` `# of the popped vertex s ` ` ` `for` `node ` `in` `self` `.adj[s]: ` ` ` `if` `(` `not` `visited[node]): ` ` ` ` ` `# If adjacent is unvisited, ` ` ` `# push it to the stack ` ` ` `visited[node] ` `=` `True` ` ` `stack.append(node) ` ` ` `# Function to return the count ` `# edges removed ` `def` `countRemovedEdges(N, M, K): ` ` ` ` ` `C ` `=` `0` ` ` ` ` `# Initially mark all verices ` ` ` `# as not visited ` ` ` `visited ` `=` `[` `False` `for` `i ` `in` `range` `(g.V ` `+` `1` `)] ` ` ` ` ` `for` `node ` `in` `range` `(` `1` `, N ` `+` `1` `): ` ` ` ` ` `# If node is unvisited ` ` ` `if` `(` `not` `visited[node]): ` ` ` ` ` `# Increment Connected ` ` ` `# component count by 1 ` ` ` `C ` `=` `C ` `+` `1` ` ` ` ` `# Perform DFS Traversal ` ` ` `g.DFS(node, visited) ` ` ` ` ` `# Print the result ` ` ` `if` `C <` `=` `K: ` ` ` `print` `(M ` `-` `N ` `+` `K) ` ` ` `else` `: ` ` ` `print` `(` `-` `1` `) ` ` ` ` ` `# Driver Code ` ` ` `N, M, K ` `=` `4` `, ` `3` `, ` `2` ` ` `# Create Graph ` `g ` `=` `Graph(N) ` ` ` `# Given Edges ` `g.addEdge(` `1` `, ` `2` `) ` `g.addEdge(` `2` `, ` `3` `) ` `g.addEdge(` `3` `, ` `4` `) ` ` ` `# Function Call ` `countRemovedEdges(N, M, K) ` |

*chevron_right*

*filter_none*

**Output:**

1

**Time Complexity:** O(N + M)**Auxiliary Space:** O(M + N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready.

## Recommended Posts:

- Maximum number of edges among all connected components of an undirected graph
- All vertex pairs connected with exactly k edges in a graph
- Convert undirected connected graph to strongly connected directed graph
- Maximum sum of values of nodes among all connected components of an undirected graph
- Maximum decimal equivalent possible among all connected components of a Binary Valued Graph
- Minimum number of edges required to be removed from an Undirected Graph to make it acyclic
- Program to count Number of connected components in an undirected graph
- Connected Components in an undirected graph
- Sum of the minimum elements in all connected components of an undirected graph
- Clone an undirected graph with multiple connected components
- Count of unique lengths of connected components for an undirected graph using STL
- Octal equivalents of connected components in Binary valued graph
- Largest subarray sum of all connected components in undirected graph
- Ways to Remove Edges from a Complete Graph to make Odd Edges
- Minimum edges required to make a Directed Graph Strongly Connected
- Maximum number of edges that N-vertex graph can have such that graph is Triangle free | Mantel's Theorem
- Shortest path with exactly k edges in a directed and weighted graph
- Shortest path in a graph from a source S to destination D with exactly K edges for multiple Queries
- Shortest path with exactly k edges in a directed and weighted graph | Set 2
- Number of connected components in a 2-D matrix of strings

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.