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: 3
💡 Note: The largest perimeter triangle can be formed with sides [1,1,1] giving perimeter 1+1+1=3. We can verify the triangle inequality: 1+1>1 ✓ for all combinations. The triangle [2,1,1] is invalid because 1+1=2 which is not > 2.
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 INPUT nums = [2, 1, 1, 1] 2 idx 0 1 idx 1 1 idx 2 1 idx 3 Triangle Inequality Rule: a + b > c Sum of 2 sides > third side Goal: Find largest perimeter of valid triangle ALGORITHM (Greedy) 1 Sort Descending [2, 1, 1, 1] 2 Check triplets Start from largest 3 Triplet (2,1,1) 1+1=2, NOT > 2 INVALID 4 Triplet (1,1,1) 1+1=2 > 1 VALID - OK Valid Triangle Found: 1 1 1 FINAL RESULT Largest Valid Triangle: 2 2 1 Perimeter Calculation: 2 + 2 + 1 = 5 Output: 5 Key Insight: Greedy approach: Sort array in descending order. For consecutive triplets (a, b, c), we only need to check b + c > a (since a is largest). First valid triplet gives maximum perimeter. TutorialsPoint - Largest Perimeter Triangle | Greedy Approach
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