Maximize count of nodes disconnected from all other nodes in a Graph
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.