Largest Perimeter Triangle
Given an integer array nums representing side lengths, return the largest possible perimeter of a triangle with non-zero area, formed from three of these lengths. If no triangle can be formed, return 0.
The triangle inequality theorem states that a triangle can be formed if the sum of any two sides is greater than the third. For a sorted array, it is sufficient to check consecutive triplets: if nums[i] + nums[i+1] > nums[i+2], these three form a valid triangle.
Sort the array descending. The largest perimeter will use the three largest lengths that satisfy the triangle inequality. Iterate through the sorted array checking each consecutive triple. Return the first valid perimeter found.
Edge cases include fewer than 3 elements (return 0), no valid triangle possible (return 0), and duplicate side lengths.
After sorting descending, the triangle inequality check on consecutive elements works because the largest perimeter will always use the largest possible sides. If the three largest sides don't form a triangle, move to the next triple.
The triangle inequality check on sorted descending elements works because any valid triangle using the largest sides will have the maximum perimeter. If sides a >= b >= c cannot form a triangle, then any smaller side will also fail when paired with a and b.Example Input & Output
3+3>4, perimeter=10.
1+1=2, no triangle.
1+2>2, sides 2,2,1 perimeter=5.
1+2=3, no triangle.
5+5>5, perimeter=15.
Algorithm Flow

Solution Approach
Sort descending. Check consecutive triples for triangle inequality. Return first valid perimeter.
Time O(n log n), Space O(1).
Best Answers
import java.util.*;
class Solution {
public int solution(int[] nums) {
Arrays.sort(nums);
for (int i=nums.length-1;i>=2;i--) {
if (nums[i]<nums[i-1]+nums[i-2]) return nums[i]+nums[i-1]+nums[i-2];
}
return 0;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
