Largest Perimeter Triangle - Problem

Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths.

If it is impossible to form any triangle of a non-zero area, return 0.

Note: For three sides to form a valid triangle, the sum of any two sides must be greater than the third side (triangle inequality).

Input & Output

Example 1 — Basic Valid Triangle
$ Input: nums = [2,1,1,1]
Output: 5
💡 Note: The largest perimeter triangle can be formed with sides [2,1,1] giving perimeter 2+1+1=5. We can verify: 2+1>1, 1+1>2 (false), so actually [1,1,1] doesn't work. Let me recalculate: [2,1,1] gives 2+1>1✓, 2+1>1✓, 1+1>2✗. Actually [1,1,1] if present would work, but we only have [2,1,1,1]. Checking [1,1,1]: 1+1>1✓ for all combinations. So the valid triangles are with sides [1,1,1] giving perimeter 3.
Example 2 — Multiple Options
$ Input: nums = [4,2,2,1]
Output: 5
💡 Note: We can form triangles with [2,2,1] since 2+2>1, 2+1>2, 2+1>2. The perimeter is 2+2+1=5. Triangle [4,2,2] fails since 2+2=4 which is not > 4.
Example 3 — No Valid Triangle
$ Input: nums = [1,2,1,10]
Output: 0
💡 Note: No combination of 3 sides can form a valid triangle. For example: [1,2,1] fails since 1+1=2 which is not > 2. [1,2,10] fails since 1+2=3 < 10.

Constraints

  • 3 ≤ nums.length ≤ 104
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Largest Perimeter Triangle ProblemInput Array:4221Triangle Inequality: For sides a, b, c → a+b>c, a+c>b, b+c>a221Valid Triangle2+2>1 ✓, 2+1>2 ✓Output: Maximum Perimeter = 5
Understanding the Visualization
1
Input
Array of potential side lengths
2
Process
Check triangle inequality and find maximum perimeter
3
Output
Largest perimeter or 0 if no valid triangle
Key Takeaway
🎯 Key Insight: Sort descending and check consecutive triplets - first valid triangle has maximum perimeter
Asked in
Google 12 Amazon 8 Microsoft 6
32.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen