Maximum Perimeter Triangle from array
Last Updated :
09 Jan, 2024
Given an array of non-negative integers. Find out three elements from this array that form a triangle of the maximum perimeter.
Examples:
Input : {6, 1, 6, 5, 8, 4}
Output : 20
Input : {2, 20, 7, 55, 1, 33, 12, 4}
Output : Triangle formation is not possible.
Input: {33, 6, 20, 1, 8, 12, 5, 55, 4, 9}
Output: 41
Naive Solution: The brute force solution is: check for all combinations of 3 elements, whether it forms a triangle or not, and update the maximum perimeter if it forms a triangle. The complexity of the naive solution is O(n3). Below is the code for it.
Implementation:
C++
#include <iostream>
#include <algorithm>
using namespace std;
void maxPerimeter( int arr[], int n){
int maxi = 0;
for ( int i = 0; i < n - 2; i++){
for ( int j = i + 1; j < n - 1; j++){
for ( int k = j + 1; k < n; k++){
int a = arr[i];
int b = arr[j];
int c = arr[k];
if (a < b+c && b < c+a && c < a+b){
maxi = max(maxi, a+b+c);
}
}
}
}
if (maxi) cout << "Maximum Perimeter is: "
<< maxi << endl;
else cout << "Triangle formation "
<< "is not possible." << endl;
}
int main()
{
int arr1[6] = {6, 1, 6, 5, 8, 4};
maxPerimeter(arr1, 6);
int arr2[8] = {2, 20, 7, 55, 1,
33, 12, 4};
maxPerimeter(arr2, 8);
int arr3[10] = {33, 6, 20, 1, 8,
12, 5, 55, 4, 9};
maxPerimeter(arr3, 10);
return 0;
}
|
Java
import java.io.*;
class GFG {
static void maxPerimeter( int arr[], int n)
{
int maxi = 0 ;
for ( int i = 0 ; i < n - 2 ; i++)
{
for ( int j = i + 1 ; j < n - 1 ; j++)
{
for ( int k = j + 1 ; k < n; k++)
{
int a = arr[i];
int b = arr[j];
int c = arr[k];
if (a < b+c && b < c+a && c < a+b)
{
maxi = Math.max(maxi, a+b+c);
}
}
}
}
if (maxi > 0 )
System.out.println( "Maximum Perimeter is: "
+ maxi);
else
System.out.println( "Triangle formation "
+ "is not possible." );
}
public static void main (String[] args)
{
int arr1[] = { 6 , 1 , 6 , 5 , 8 , 4 };
maxPerimeter(arr1, 6 );
int arr2[] = { 2 , 20 , 7 , 55 , 1 , 33 , 12 , 4 };
maxPerimeter(arr2, 8 );
int arr3[] = { 33 , 6 , 20 , 1 , 8 ,
12 , 5 , 55 , 4 , 9 };
maxPerimeter(arr3, 10 );
}
}
|
Python
def maxPerimeter(arr):
maxi = 0
n = len (arr)
for i in range (n - 2 ):
for j in range (i + 1 , n - 1 ):
for k in range (j + 1 , n):
a = arr[i]
b = arr[j]
c = arr[k]
if (a < b + c and b < a + c
and c < a + b):
maxi = max (maxi, a + b + c)
if (maxi = = 0 ):
return "Triangle formation is not possible"
else :
return "Maximum Perimeter is: " + str (maxi)
def main():
arr1 = [ 6 , 1 , 6 , 5 , 8 , 4 ]
a = maxPerimeter(arr1)
print (a)
arr2 = [ 2 , 20 , 7 , 55 ,
1 , 33 , 12 , 4 ]
a = maxPerimeter(arr2)
print (a)
arr3 = [ 33 , 6 , 20 , 1 , 8 ,
12 , 5 , 55 , 4 , 9 ]
a = maxPerimeter(arr3)
print (a)
if __name__ = = '__main__' :
main()
|
C#
using System;
class GFG
{
static void maxPerimeter( int []arr,
int n)
{
int maxi = 0;
for ( int i = 0; i < n - 2; i++)
{
for ( int j = i + 1; j < n - 1; j++)
{
for ( int k = j + 1; k < n; k++)
{
int a = arr[i];
int b = arr[j];
int c = arr[k];
if (a < b + c &&
b < c + a &&
c < a + b)
{
maxi = Math.Max(maxi, a + b + c);
}
}
}
}
if (maxi > 0)
Console.WriteLine( "Maximum Perimeter is: " + maxi);
else
Console.WriteLine( "Triangle formation " +
"is not possible." );
}
public static void Main ()
{
int []arr1 = {6, 1, 6,
5, 8, 4};
maxPerimeter(arr1, 6);
int []arr2 = {2, 20, 7, 55,
1, 33, 12, 4};
maxPerimeter(arr2, 8);
int []arr3 = {33, 6, 20, 1, 8,
12, 5, 55, 4, 9};
maxPerimeter(arr3, 10);
}
}
|
Javascript
<script>
function maxPerimeter(arr, n)
{
let maxi = 0;
for (let i = 0; i < n - 2; i++)
{
for (let j = i + 1; j < n - 1; j++)
{
for (let k = j + 1; k < n; k++)
{
let a = arr[i];
let b = arr[j];
let c = arr[k];
if (a < b+c && b < c+a && c < a+b)
{
maxi = Math.max(maxi, a+b+c);
}
}
}
}
if (maxi > 0)
document.write( "Maximum Perimeter is: "
+ maxi + "<br/>" );
else
document.write( "Triangle formation "
+ "is not possible." + "<br/>" );
}
let arr1 = [6, 1, 6, 5, 8, 4];
maxPerimeter(arr1, 6);
let arr2 = [2, 20, 7, 55, 1, 33, 12, 4];
maxPerimeter(arr2, 8);
let arr3 = [33, 6, 20, 1, 8,
12, 5, 55, 4, 9];
maxPerimeter(arr3, 10);
</script>
|
PHP
<?php
function maxPerimeter( $arr , $n )
{
$maxi = 0;
for ( $i = 0; $i < $n - 2; $i ++)
{
for ( $j = $i + 1; $j < $n - 1; $j ++)
{
for ( $k = $j + 1; $k < $n ; $k ++)
{
$a = $arr [ $i ];
$b = $arr [ $j ];
$c = $arr [ $k ];
if ( $a < $b + $c and
$b < $c + $a and
$c < $a + $b )
{
$maxi = max( $maxi , $a + $b + $c );
}
}
}
}
if ( $maxi )
{
echo "Maximum Perimeter is: " ;
echo $maxi , "\n" ;
}
else
{
echo "Triangle formation " ;
echo "is not possible. \n" ;
}
}
$arr1 = array (6, 1, 6, 5, 8, 4);
maxPerimeter( $arr1 , 6);
$arr2 = array (2, 20, 7, 55,
1, 33, 12, 4);
maxPerimeter( $arr2 , 8);
$arr3 = array (33, 6, 20, 1, 8,
12, 5, 55, 4, 9);
maxPerimeter( $arr3 , 10);
?>
|
Output
Maximum Perimeter is: 20
Triangle formation is not possible.
Maximum Perimeter is: 41
Auxiliary Space : O(1)
Efficient Approach:
First, we can sort the array in non-increasing order. So, the first element will be the maximum and the last will be the minimum. Now if the first 3 elements of this sorted array form a triangle, then it will be the maximum perimeter triangle, as for all other combinations the sum of elements(i.e. the perimeter of that triangle) will be = b >= c). a, b,c can not form a triangle, so a >= b + c. As, b and c = c+d (if we drop b and take d) or a >= b+d (if we drop c and take d). So, we have to drop a and pick up d.
Again, the same set of analysis for b, c, and d. We can continue this till end and whenever we find a triangle forming a triple, then we can stop checking, as this triple gives a maximum perimeter.
Hence, if arr[i] < arr[i+1] + arr[i+2] (0 <= i <= n-3)in the sorted array, then arr[i], arr[i+1] and arr[i+2] form a triangle.
Below is the simple implementation of this concept:
C++
#include <iostream>
#include <algorithm>
using namespace std;
void maxPerimeter( int arr[], int n){
sort(arr, arr+n, greater< int >());
int maxi = 0;
for ( int i = 0; i < n-2; i++){
if (arr[i] < arr[i+1] + arr[i+2]){
maxi = max(maxi, arr[i] + arr[i+1] + arr[i+2]);
break ;
}
}
if (maxi)
cout << "Maximum Perimeter is: "
<< maxi << endl;
else
cout << "Triangle formation"
<< "is not possible." << endl;
}
int main()
{
int arr1[6] = {6, 1, 6, 5, 8, 4};
maxPerimeter(arr1, 6);
int arr2[8] = {2, 20, 7, 55, 1,
33, 12, 4};
maxPerimeter(arr2, 8);
int arr3[10] = {33, 6, 20, 1, 8,
12, 5, 55, 4, 9};
maxPerimeter(arr3, 10);
return 0;
}
|
Java
import java.util.Arrays;
class GFG {
static void maxPerimeter( int arr[], int n) {
arr = arrRevSort(arr);
int maxi = 0 ;
for ( int i = 0 ; i < n - 2 ; i++) {
if (arr[i] < arr[i + 1 ] + arr[i + 2 ]) {
maxi = Math.max(maxi, arr[i] + arr[i + 1 ] + arr[i + 2 ]);
break ;
}
}
if (maxi > 0 ) {
System.out.println( "Maximum Perimeter is: " + maxi);
}
else {
System.out.println( "Triangle formation is not possible." );
}
}
static int [] arrRevSort( int [] arr) {
Arrays.sort(arr, 0 , arr.length);
int j = arr.length - 1 ;
for ( int i = 0 ; i < arr.length / 2 ; i++, j--) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
}
public static void main(String[] args) {
int arr1[] = { 6 , 1 , 6 , 5 , 8 , 4 };
maxPerimeter(arr1, 6 );
int arr2[] = { 2 , 20 , 7 , 55 , 1 , 33 , 12 , 4 };
maxPerimeter(arr2, 8 );
int arr3[] = { 33 , 6 , 20 , 1 , 8 , 12 , 5 , 55 , 4 , 9 };
maxPerimeter(arr3, 10 );
}
}
|
Python3
def maxPerimeter(arr):
maxi = 0
n = len (arr)
arr.sort(reverse = True )
for i in range ( 0 , n - 2 ):
if arr[i] < (arr[i + 1 ] + arr[i + 2 ]):
maxi = max (maxi, arr[i] +
arr[i + 1 ] + arr[i + 2 ])
break
if (maxi = = 0 ):
return "Triangle formation is not possible"
else :
return "Maximum Perimeter is: " + str (maxi)
def main():
arr1 = [ 6 , 1 , 6 , 5 , 8 , 4 ]
a = maxPerimeter(arr1)
print (a)
arr2 = [ 2 , 20 , 7 , 55 ,
1 , 33 , 12 , 4 ]
a = maxPerimeter(arr2)
print (a)
arr3 = [ 33 , 6 , 20 , 1 , 8 ,
12 , 5 , 55 , 4 , 9 ]
a = maxPerimeter(arr3)
print (a)
if __name__ = = '__main__' :
main()
|
C#
using System;
class GFG {
static void maxPerimeter( int [] arr, int n) {
arr = arrRevSort(arr);
int maxi = 0;
for ( int i = 0; i < n - 2; i++) {
if (arr[i] < arr[i + 1] + arr[i + 2]) {
maxi = Math.Max(maxi, arr[i] + arr[i + 1] + arr[i + 2]);
break ;
}
}
if (maxi > 0) {
Console.WriteLine( "Maximum Perimeter is: " + maxi);
}
else {
Console.WriteLine( "Triangle formation is not possible." );
}
}
static int [] arrRevSort( int [] arr) {
Array.Sort(arr);
int j = arr.Length - 1;
for ( int i = 0; i < arr.Length / 2; i++, j--) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
}
public static void Main() {
int [] arr1 = {6, 1, 6, 5, 8, 4};
maxPerimeter(arr1, 6);
int [] arr2 = {2, 20, 7, 55, 1, 33, 12, 4};
maxPerimeter(arr2, 8);
int [] arr3 = {33, 6, 20, 1, 8, 12, 5, 55, 4, 9};
maxPerimeter(arr3, 10);
}
}
|
Javascript
<script>
function maxPerimeter(arr, n){
arr.sort( function (a, b){ return a - b});
arr.reverse();
let maxi = 0;
for (let i = 0; i < n-2; i++){
if (arr[i] < arr[i+1] + arr[i+2]){
maxi = Math.max(maxi, arr[i] + arr[i+1] + arr[i+2]);
break ;
}
}
if (maxi)
document.write( "Maximum Perimeter is: " + maxi + "</br>" );
else
document.write( "Triangle formation is not possible." + "</br>" );
}
let arr1 = [6, 1, 6, 5, 8, 4];
maxPerimeter(arr1, 6);
let arr2 = [2, 20, 7, 55, 1, 33, 12, 4];
maxPerimeter(arr2, 8);
let arr3 = [33, 6, 20, 1, 8, 12, 5, 55, 4, 9];
maxPerimeter(arr3, 10);
</script>
|
PHP
<?php
function maxPerimeter(& $arr , $n )
{
rsort( $arr );
$maxi = 0;
for ( $i = 0; $i < $n - 2; $i ++)
{
if ( $arr [ $i ] < $arr [ $i + 1] +
$arr [ $i + 2])
{
$maxi = max( $maxi , $arr [ $i ] +
$arr [ $i + 1] +
$arr [ $i + 2]);
break ;
}
}
if ( $maxi )
{
echo ( "Maximum Perimeter is: " );
echo ( $maxi ) ;
echo ( "\n" );
}
else
{
echo ( "Triangle formation " );
echo ( "is not possible." );
echo ( "\n" );
}
}
$arr1 = array (6, 1, 6, 5, 8, 4);
$s = sizeof( $arr1 );
maxPerimeter( $arr1 , $s );
$arr2 = array (2, 20, 7, 55, 1,33, 12, 4);
$st = sizeof( $arr2 );
maxPerimeter( $arr2 , $st );
$arr3 = array (33, 6, 20, 1, 8,
12, 5, 55, 4, 9);
$st1 = sizeof( $arr3 );
maxPerimeter( $arr3 , $st1 );
?>
|
Output
Maximum Perimeter is: 20
Triangle formationis not possible.
Maximum Perimeter is: 41
Complexity Analysis:
- Time complexity: O(n*log(n)). This much time is required to sort the array.
- Space complexity: O(1) since constant space is used.
Efficient Approach with Math:
This approach is more on mathematical side. As we discussed the efficient approach above. There we sort the array then simulate the every three elements to get the maximum perimeter but also they should satisfy the a+b>c triangle condition. But this approach is rarely seen. I claim that fibonacci sequence is the almost possible(but it does not satisfy the condition a+b>c) triangle rule satisfying sequence where a+b=c.
According to constraints, we can fix the number of elements we should iterate instead of iterating whole array. For example, If our every element lies in 1e9 then we only need to check the 45 max elements of the array to get the max perimeter and If those 45 don’t give a valid answer then rest of the elements can’t form a triangle. So, As per many Coding platforms, the element value will mostly be <=1e9.
Why only 45 elements?
- fibo(45) is 1134903170. As it is greater than 1e9.
- As it is in 45th place in the sequence.
- In fibo sequence, elements don’t obey the triangle rule but they almost do it. So it is possible to have only 45 elements before a number if our right-most number is at max 1e9. If it is increased then also we can fix it. This trick is helpful in complex triangle problems.
C++
#include <bits/stdc++.h>
using namespace std;
int maxPerimeter( int arr[], int n){
sort(arr, arr+n, greater< int >());
for ( int i = 0,j=1; i < n-2 &&j<=45; i++,j++){
if (arr[i] < arr[i+1] + arr[i+2]){
return arr[i]+arr[i+1]+arr[i+2];
}
}
return 0;
}
void print( int ans){
if (ans)
cout << "Maximum Perimeter is: "
<< ans << endl;
else
cout << "Triangle formation"
<< " is not possible." << endl;
}
int main()
{
int arr1[6] = {6, 1, 6, 5, 8, 4};
print(maxPerimeter(arr1, 6));
int arr2[8] = {2, 20, 7, 55, 1,
33, 12, 4};
print(maxPerimeter(arr2, 8));
int arr3[10] = {33, 6, 20, 1, 8,
12, 5, 55, 4, 9};
print(maxPerimeter(arr3, 10));
return 0;
}
|
Java
import java.util.Arrays;
import java.util.Collections;
public class Main {
static int maxPerimeter( int [] arr, int n) {
Integer[] arrInteger = new Integer[n];
for ( int i = 0 ; i < n; i++) {
arrInteger[i] = arr[i];
}
Arrays.sort(arrInteger, Collections.reverseOrder());
for ( int i = 0 , j = 1 ; i < n - 2 && j <= 45 ; i++, j++) {
if (arrInteger[i] < arrInteger[i + 1 ] + arrInteger[i + 2 ]) {
return arrInteger[i] + arrInteger[i + 1 ] + arrInteger[i + 2 ];
}
}
return 0 ;
}
static void print( int ans) {
if (ans != 0 ) {
System.out.println( "Maximum Perimeter is: " + ans);
} else {
System.out.println( "Triangle formation is not possible." );
}
}
public static void main(String[] args) {
int [] arr1 = { 6 , 1 , 6 , 5 , 8 , 4 };
print(maxPerimeter(arr1, 6 ));
int [] arr2 = { 2 , 20 , 7 , 55 , 1 , 33 , 12 , 4 };
print(maxPerimeter(arr2, 8 ));
int [] arr3 = { 33 , 6 , 20 , 1 , 8 , 12 , 5 , 55 , 4 , 9 };
print(maxPerimeter(arr3, 10 ));
}
}
|
Python3
def max_perimeter(arr):
arr.sort(reverse = True )
for i in range ( len (arr) - 2 ):
if arr[i] < arr[i + 1 ] + arr[i + 2 ]:
return arr[i] + arr[i + 1 ] + arr[i + 2 ]
return 0
def print_result(ans):
if ans:
print ( "Maximum Perimeter is:" , ans)
else :
print ( "Triangle formation is not possible." )
arr1 = [ 6 , 1 , 6 , 5 , 8 , 4 ]
print_result(max_perimeter(arr1))
arr2 = [ 2 , 20 , 7 , 55 , 1 , 33 , 12 , 4 ]
print_result(max_perimeter(arr2))
arr3 = [ 33 , 6 , 20 , 1 , 8 , 12 , 5 , 55 , 4 , 9 ]
print_result(max_perimeter(arr3))
|
C#
using System;
class Program
{
static int MaxPerimeter( int [] arr)
{
Array.Sort(arr, (a, b) => b.CompareTo(a));
for ( int i = 0, j = 1; i < arr.Length - 2 && j <= 45; i++, j++)
{
if (arr[i] < arr[i + 1] + arr[i + 2])
{
return arr[i] + arr[i + 1] + arr[i + 2];
}
}
return 0;
}
static void Print( int ans)
{
if (ans != 0)
Console.WriteLine( "Maximum Perimeter is: " + ans);
else
Console.WriteLine( "Triangle formation is not possible." );
}
static void Main()
{
int [] arr1 = { 6, 1, 6, 5, 8, 4 };
Print(MaxPerimeter(arr1));
int [] arr2 = { 2, 20, 7, 55, 1, 33, 12, 4 };
Print(MaxPerimeter(arr2));
int [] arr3 = { 33, 6, 20, 1, 8, 12, 5, 55, 4, 9 };
Print(MaxPerimeter(arr3));
}
}
|
Javascript
function maxPerimeter(arr) {
arr.sort((a, b) => b - a);
for (let i = 0; i < arr.length - 2; i++) {
if (arr[i] < arr[i + 1] + arr[i + 2]) {
return arr[i] + arr[i + 1] + arr[i + 2];
}
}
return 0;
}
function printResult(ans) {
if (ans) {
console.log( "Maximum Perimeter is:" , ans);
} else {
console.log( "Triangle formation is not possible." );
}
}
let arr1 = [6, 1, 6, 5, 8, 4];
printResult(maxPerimeter(arr1));
let arr2 = [2, 20, 7, 55, 1, 33, 12, 4];
printResult(maxPerimeter(arr2));
let arr3 = [33, 6, 20, 1, 8, 12, 5, 55, 4, 9];
printResult(maxPerimeter(arr3));
|
Output:
Maximum Perimeter is: 20
Triangle formation is not possible.
Maximum Perimeter is: 41
Time Complexity: O(NlogN + 45)
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...