# Maximum Perimeter Triangle from array 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

66 Lectures 5.5 hours

## Problem statement

Given an Array of non-negative integers. Find out three elements from the array which form a triangle of maximum perimeter

## Example

If input array is {5, 1, 3, 5, 7, 4} then maximum perimeter is (7 + 5 + 5) = 17

## Algorithm

• Sort the array in non-increasing order. So, the first element will be maximum and the last will be minimum
• If the first 3 elements of this sorted array forms a triangle, then it will be the maximum perimeter triangle

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int getMaxPerimeter(int *arr, int n) {
sort(arr, arr + n, greater<int>());
int maxPerimeter = 0;
for (int i = 0; i < n - 2; ++i) {
if (arr[i] < arr[i + 1] + arr[i + 2]) {
maxPerimeter = max(maxPerimeter, arr[i]
+ arr[i+1] + arr[i+2]);
break;
}
}
if (maxPerimeter) {
return maxPerimeter;
}
return -1;
}
int main() {
int arr[] = {5, 1, 3, 5, 7, 4};
int n = sizeof(arr) / sizeof(arr);
int maxPerimeter;
maxPerimeter = getMaxPerimeter(arr, n);
if (maxPerimeter != -1) {
cout << "Max perimeter = " << maxPerimeter <<
endl;
} else {
cout << "Triangle formation is not possible" <<
endl;
}
return 0;
}

## Output

When you compile and execute above program. It generates following output −

Max perimeter = 17