Maximum Perimeter Triangle from array in C++

C++Server Side ProgrammingProgramming

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[0]);
   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
raja
Published on 21-Jan-2020 10:56:32
Advertisements