VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-perimeter-triangle-from-array/

⇱ Maximum Perimeter Triangle from array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum Perimeter Triangle from array

Last Updated : 23 Apr, 2025

Given an array arr[] of positive integers. Find out the maximum perimeter of the triangle from the array.

Note: Return -1, if it is not possible to construct a triangle.

Examples:

Input: arr[] = [6, 1, 6, 5, 8, 4]
Output: 20
Explanation: Triangle formed by  8,6 & 6 has perimeter 20, which is the max possible.

Input: arr[] = [7, 55, 20, 1, 4, 33, 12]
Output: -1
Explanation: The triangle is not possible because the condition: the sum of two sides should be greater than third is not fulfilled here.

[Naive Approach] - Using Nested Loops - O(n ^ 3) Time and O(1) Space

The idea is to check for all possible combinations of three integers using nested loops, whether it forms a valid triangle (the sum of any two must be more than the third), if so, update the maximum possible perimeter.


Output
20

[Expected Approach] - Using Sorting - (n * log n) Time and O(1) Space

The idea is to sort the array in non-increasing order so that the first element is the maximum and the last is the minimum. Then for every three consecutive elements, check if they form a triangle, the first such combination is the required answer.

Please note that, we pick the first arr[i] such that arr[i] < arr[i+1] + arr[i+2] (0 <= i <= n-3).

How does this work? For any arr[i] to be part of the triangle, it must be smaller than sum of other two. In a decreasing order sorted array if arr[i] is greater than or equal to arr[i+1] + arr[i+2], then it would be greater than all other pairs after arr[i+1]. So there is no point checking other pairs. So after sorting, we only need to check the next 2, Since the array is sorted in decreasing order, the first arr[i] satisfying the condition from left to right would give us the max result.

Below is given the step-by-step approach:

  • First, sort the array in non-increasing order.
  • Then, check the first three elements of the sorted array. If they satisfy the triangle inequality (i.e. arr[i] < arr[i+1] + arr[i+2]), they form a triangle with the maximum possible perimeter because any other combination will result in a lower sum.
  • If the first three elements do not form a triangle, it implies that the largest element is too large (i.e., a ≥ b + c), so drop the largest element and consider the next triple.
  • Repeat the process by checking consecutive triples (i.e., b, c, d; then c, d, e; and so on) until a valid triangle is found.
  • Once a valid triple is identified, it gives the maximum perimeter, and further checking is unnecessary.

Below is given the implementation:


Output
20
Comment
Article Tags: