Check if it is possible to create a polygon with given n sides
Last Updated :
17 Feb, 2023
Given an array arr[] that contains the lengths of n sides that may or may not form a polygon. The task is to determine whether it is possible to form a polygon with all the given sides. Print Yes if possible else print No.
Examples:
Input: arr[] = {2, 3, 4}
Output: Yes
Input: arr[] = {3, 4, 9, 2}
Output: No
Approach: In order to create a polygon with given n sides, there is a certain property that must be satisfied by the sides of the polygon.
Property: The length of the every given side must be less than the sum of the other remaining sides.
Find the largest side among the given sides. Then, check whether it is smaller than the sum of the other sides or not. If it is smaller than print Yes else print No.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPossible( int a[], int n)
{
int sum = 0, maxS = 0;
for ( int i = 0; i < n; i++) {
sum += a[i];
maxS = max(a[i], maxS);
}
if ((sum - maxS) > maxS)
return true ;
return false ;
}
int main()
{
int a[] = { 2, 3, 4 };
int n = sizeof (a) / sizeof (a[0]);
if (isPossible(a, n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
class GFG {
static boolean isPossible( int a[], int n)
{
int sum = 0 , maxS = 0 ;
for ( int i = 0 ; i < n; i++) {
sum += a[i];
maxS = Math.max(a[i], maxS);
}
if ((sum - maxS) > maxS)
return true ;
return false ;
}
public static void main(String[] args)
{
int a[] = { 2 , 3 , 4 };
int n = a.length;
if (isPossible(a, n))
System.out.print( "Yes" );
else
System.out.print( "No" );
}
}
|
Python
def isPossible(a, n):
sum = 0
maxS = 0
for i in range (n):
sum + = a[i]
maxS = max (a[i], maxS)
if (( sum - maxS) > maxS):
return True
return False
a = [ 2 , 3 , 4 ]
n = len (a)
if (isPossible(a, n)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG {
static bool isPossible( int [] a, int n)
{
int sum = 0, maxS = 0;
for ( int i = 0; i < n; i++) {
sum += a[i];
maxS = Math.Max(a[i], maxS);
}
if ((sum - maxS) > maxS)
return true ;
return false ;
}
static void Main()
{
int [] a = { 2, 3, 4 };
int n = a.Length;
if (isPossible(a, n))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
PHP
<?php
function isPossible( $a , $n )
{
$sum = 0;
$maxS = 0;
for ( $i = 0; $i < $n ; $i ++) {
$sum += $a [ $i ];
$maxS = max( $a [ $i ], $maxS );
}
if (( $sum - $maxS ) > $maxS )
return true;
return false;
}
$a = array (2, 3, 4);
$n = count ( $a );
if (isPossible( $a , $n ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function isPossible( a, n)
{
let sum = 0, maxS = 0;
for (let i = 0; i < n; i++) {
sum += a[i];
maxS = Math.max(a[i], maxS);
}
if ((sum - maxS) > maxS)
return true ;
return false ;
}
let a = [ 2, 3, 4 ];
let n = a.length;
if (isPossible(a, n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...