Given two integers N and E which denotes the number of nodes and the number of edges of an undirected graph, the task is to maximize the number of nodes which is not connected to any other node in the graph, without using any self-loops.
Input: N = 5, E = 1
Since there is only 1 edge in the graph which can be used to connect two nodes.
Therefore, three node remains disconnected.
Input: N = 5, E = 2
Approach: The approach is based on the idea that to maximize the number of disconnected nodes, the new nodes will not be added to the graph until every two distinct nodes become connected. Below are the steps to solve this problem:
- Initialize two variables curr and rem to store the nodes connected and the edges remaining unassigned respectively.
- If rem becomes 0, then the required answer will be N – curr.
- Otherwise, increment the value of curr by 1.
- So, the maximum edges needed in the current step to keep every two distinct nodes connected is min(rem, curr). Subtract it from rem and increment curr.
- Repeat this process until rem reduces to zero.
- Finally, print N – curr.
Below is the implementation of the above approach:
Time Complexity: O(E)
Auxiliary Space: O(1)
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.
- Count single node isolated sub-graphs in a disconnected graph
- BFS for Disconnected Graph
- Maximize path sum from top-left cell to all other cells of a given Matrix
- Maximize number of nodes which are not part of any edge in a Graph
- Detect cycle in the graph using degrees of nodes of graph
- Length of array pair formed where one contains all distinct elements and other all same elements
- Count of elements whose absolute difference with the sum of all the other elements is greater than k
- Count nodes within K-distance from all nodes in a set
- Sum of degrees of all nodes of a undirected graph
- Kth largest node among all directly connected nodes to the given node in an undirected graph
- Maximum sum of values of nodes among all connected components of an undirected graph
- Graph implementation using STL for competitive programming | Set 2 (Weighted graph)
- Convert the undirected graph into directed graph such that there is no path of length greater than 1
- Maximum number of edges that N-vertex graph can have such that graph is Triangle free | Mantel's Theorem
- Convert undirected connected graph to strongly connected directed graph
- Maximize sum of minimum difference of divisors of nodes in N-ary tree
- Count of all cycles without any inner cycle in a given Graph
- Count permutations of all integers upto N that can form an acyclic graph based on given conditions
- Replace every element of the array by product of all other elements
- Check whether the cost of going from any node to any other node via all possible paths is same