Find the maximum number of handshakes
Last Updated :
02 May, 2022
There are N persons in a room. Find the maximum number of Handshakes possible. Given the fact that any two persons shake hand exactly once.
Examples :
Input : N = 2
Output : 1.
There are only 2 persons in the room. 1 handshake take place.
Input : N = 10
Output : 45.
To maximize the number of handshakes, each person should shake hand with every other person in the room. For the first person, there would be N-1 handshakes. For second person there would N-1 person available but he had already shaken hand with the first person. So there would be N-2 handshakes and so on.
So, Total number of handshake = N-1 + N-2 +….+ 1 + 0, which is equivalent to ((N-1)*N)/2
(using the formula of sum of first N natural number).
Below is the implementation of this problem.
C++
#include <bits/stdc++.h>
using namespace std;
int maxHandshake( int n) { return (n * (n - 1)) / 2; }
int main()
{
int n = 10;
cout << maxHandshake(n) << endl;
return 0;
}
|
C
#include <stdio.h>
int maxHandshake( int n) { return (n * (n - 1)) / 2; }
int main()
{
int n = 10;
printf ( "%d\n" , maxHandshake(n));
return 0;
}
|
Java
class GFG {
static int maxHandshake( int n)
{
return (n * (n - 1 )) / 2 ;
}
public static void main(String[] args)
{
int n = 10 ;
System.out.println(maxHandshake(n));
}
}
|
Python3
def maxHandshake(n):
return int ((n * (n - 1 )) / 2 )
n = 10
print (maxHandshake(n))
|
C#
using System;
class GFG
{
static int maxHandshake( int n)
{
return (n * (n - 1)) / 2;
}
public static void Main ()
{
int n = 10;
Console.Write( maxHandshake(n));
}
}
|
PHP
<?php
function maxHandshake( $n )
{
return ( $n * ( $n - 1))/ 2;
}
$n = 10;
echo maxHandshake( $n );
?>
|
Javascript
<script>
function maxHandshake(n)
{
return (n * (n - 1)) / 2;
}
let n = 10;
document.write( maxHandshake(n));
</script>
|
Output:
45
Time Complexity : O(1)
Share your thoughts in the comments
Please Login to comment...