# Maximize number of nodes which are not part of any edge in a Graph in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

We are given a graph containing nodes and edges. The goal is to find the maximum number of possible nodes that are connected to any edge of the graph. We know that no. of nodes will always be less than or equal to the number of edges in a complete graph.

We will do this by trying to make a complete graph where the number of nodes is n then there will be n(n-1)/2 edges.

edge=n(n-1)/2 (here n for nodes )

2*edge=n(n-1). Once n(n-1)> no. of edges then we have extra nodes. So iterate from i=1 to i=n.

Till i(i-1)>2*edge. Return n-i as result.

Let us understand with examples −

Input − nodes=5, edges=2

Output − Maximize number of nodes which are not part of any edge in a Graph are − 2

Explanation

2 edges can have minimum 3 nodes and maximum 4 nodes.

For 3 nodes maximum left nodes without any edge=2

Input − nodes=2, edges=1

Output − Maximize number of nodes which are not part of any edge in a Graph are − 0

Explanation

At Least 2 nodes are required to make an edge. In this case both are occupied. No node left.

## Approach used in the below program is as follows

• We take two variable nodes and edges for available data.

• Function maximum(int nodes, int edges) takes no. of nodes and edges as parameters and returns the count of maximum nodes that are not part of any edge in a Graph

• Take variables i, temp and max.

• Start loop FOR from i=0 to i<=nodes

• Calculate temp=i*(i-1)

• Calculate variable total as 2*edges

• Whenever temp becomes more than total, break the FOR

• Calculate max as max=nodes-i

• Return the result as max.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int maximum(int nodes, int edges){
int i, temp = 0, max;
for (i = 0; i <= nodes; i++){
temp = i * (i - 1);
int total = 2* edges;
if (temp >= total){
break;
}
}
max = nodes - i;
return max;
}
int main(){
int nodes = 10;
int edges = 5;
cout<<"Maximize number of nodes which are not part of any edge in a Graph are:"<<maximum(nodes, edges) << endl;
}

## Output

If we run the above code it will generate the following output −

Maximize number of nodes which are not part of any edge in a Graph are: 6
Updated on 31-Aug-2020 08:31:49