Largest Perimeter Triangle - Problem
Given an integer array nums of positive integers, your task is to find three numbers that can form a valid triangle with the largest possible perimeter.
A valid triangle must satisfy the triangle inequality theorem: the sum of any two sides must be greater than the third side. For three sides a, b, and c, we need:
a + b > ca + c > bb + c > a
Return the largest perimeter of such a triangle. If no valid triangle can be formed, return 0.
Example: Given [2, 1, 2], we can form a triangle with sides 2, 1, 2 having perimeter = 5. Given [1, 2, 1], we can form the same triangle. But given [3, 2, 3, 4], the best triangle uses sides 2, 3, 4 with perimeter = 9.
Input & Output
example_1.py โ Basic Triangle
$
Input:
[2,1,2]
โบ
Output:
5
๐ก Note:
The only possible triangle uses all three sides: 2, 1, 2. We verify: 2+1>2 โ, 2+2>1 โ, 1+2>2 โ. Perimeter = 2+1+2 = 5.
example_2.py โ Multiple Triangles
$
Input:
[1,2,1,10]
โบ
Output:
0
๐ก Note:
No valid triangle can be formed. The sides 1,2,1 don't satisfy triangle inequality (1+1 = 2, not > 2), and any combination with 10 fails because 10 is too large compared to other sides.
example_3.py โ Optimal Selection
$
Input:
[3,2,3,4]
โบ
Output:
10
๐ก Note:
Multiple triangles possible: (3,2,3) with perimeter 8, (2,3,4) with perimeter 9, and (3,3,4) with perimeter 10. The maximum is 10.
Constraints
- 3 โค nums.length โค 104
- 1 โค nums[i] โค 106
- All elements are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Arrange planks by length
Sort all available planks from longest to shortest
2
Try largest combinations first
Start with the three longest planks and check if they form a valid triangle
3
Apply triangle rule
For sorted planks aโฅbโฅc, only check if b+c>a (other inequalities are automatically satisfied)
4
First valid = optimal
The first valid triangle found has maximum perimeter
Key Takeaway
๐ฏ Key Insight: By sorting in descending order and checking consecutive triplets, we guarantee that the first valid triangle found has the maximum possible perimeter, eliminating the need to check all combinations.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code