Maximize number of nodes which are not part of any edge in a Graph
Last Updated :
06 Sep, 2022
Given a graph with n nodes and m edges. Find the maximum possible number of nodes which are not part of any edge (m will always be less than or equal to a number of edges in complete graph).
Examples:
Input: n = 3, m = 3
Output: Maximum Nodes Left Out: 0
Since it is a complete graph.
Input: n = 7, m = 6
Output: Maximum Nodes Left Out: 3
We can construct a complete graph on 4 vertices using 6 edges.
Approach: Iterate over all n and see at which a number of nodes if we make a complete graph we obtain a number of edges more than m say it is K. Answer is n-k.
- Maximum number of edges which can be used to form a graph on n nodes is n * (n – 1) / 2 (A complete Graph).
- Then find number of maximum n, which will use m or less than m edges to form a complete graph.
- If still edges are left, then it will cover only one more node, as if it would have covered more than one node than, this is not the maximum value of n.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
int answer( int n, int m)
{
int i;
for (i = 0; i <= n; i++) {
if ((i * (i - 1)) >= 2 * m)
break ;
}
return n - i;
}
int main()
{
int n = 7;
int m = 6;
cout << answer(n, m) << endl;
}
|
Java
import java.io.*;
class GFG {
static int answer( int n, int m)
{
int i;
for (i = 0 ; i <= n; i++) {
if ((i * (i - 1 )) >= 2 * m)
break ;
}
return n - i;
}
public static void main (String[] args) {
int n = 7 ;
int m = 6 ;
System.out.print( answer(n, m));
}
}
|
Python3
def answer(n, m):
for i in range ( 0 , n + 1 , 1 ):
if ((i * (i - 1 )) > = 2 * m):
break
return n - i
if __name__ = = '__main__' :
n = 7
m = 6
print (answer(n, m))
|
C#
using System;
class GFG
{
static int answer( int n, int m)
{
int i;
for (i = 0; i <= n; i++)
{
if ((i * (i - 1)) >= 2 * m)
break ;
}
return n - i;
}
static public void Main ()
{
int n = 7;
int m = 6;
Console.WriteLine(answer(n, m));
}
}
|
PHP
<?php
function answer( $n , $m )
{
for ( $i = 0; $i <= $n ; $i ++)
{
if (( $i * ( $i - 1)) >= 2 * $m )
break ;
}
return $n - $i ;
}
$n = 7;
$m = 6;
echo answer( $n , $m ) + "\n" ;
?>
|
Javascript
<script>
function answer(n, m)
{
let i;
for (i = 0; i <= n; i++) {
if ((i * (i - 1)) >= 2 * m)
break ;
}
return n - i;
}
let n = 7;
let m = 6;
document.write( answer(n, m));
</script>
|
Complexity Analysis:
- Time Complexity: O(n) where n is the number of nodes.
- Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...