Find Polygon With the Largest Perimeter - Problem
You are given an array of positive integers nums of length n.
A polygon is a closed plane figure that has at least 3 sides. The longest side of a polygon is smaller than the sum of its other sides.
Conversely, if you have k (k ≥ 3) positive real numbers a₁, a₂, a₃, ..., aₖ where a₁ ≤ a₂ ≤ a₃ ≤ ... ≤ aₖ and a₁ + a₂ + a₃ + ... + aₖ₋₁ > aₖ, then there always exists a polygon with k sides whose lengths are a₁, a₂, a₃, ..., aₖ.
The perimeter of a polygon is the sum of lengths of its sides.
Return the largest possible perimeter of a polygon whose sides can be formed from nums, or -1 if it is not possible to create a polygon.
Input & Output
Example 1 — Basic Valid Polygon
$
Input:
nums = [5,5,5,2,10,15]
›
Output:
42
💡 Note:
After sorting: [2,5,5,5,10,15]. All elements form a valid polygon because 15 < 2+5+5+5+10 = 27. Total perimeter = 42.
Example 2 — No Valid Polygon
$
Input:
nums = [1,12,1,2,5,50,3]
›
Output:
-1
💡 Note:
After sorting: [1,1,2,3,5,12,50]. No subset can form a valid polygon because any combination with 50 fails (50 ≥ sum of others), and without 50, 12 ≥ sum of remaining elements.
Example 3 — Minimum Size Triangle
$
Input:
nums = [3,3,5]
›
Output:
11
💡 Note:
After sorting: [3,3,5]. Forms valid triangle since 5 < 3+3 = 6. Perimeter = 3+3+5 = 11.
Constraints
- 3 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array of positive integers representing potential side lengths
2
Sort & Check
Sort elements and find largest valid polygon combination
3
Return Perimeter
Sum of all sides in the largest valid polygon
Key Takeaway
🎯 Key Insight: Sort the array and greedily check from largest combinations - the first valid polygon found will have the maximum perimeter
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code