![]() |
VOOZH | about |
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.
Table of Content
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.
20
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:
Below is given the implementation:
20