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
Find Polygon With the Largest Perimeter INPUT nums = [5, 5, 5, 2, 10, 15] 5 5 5 2 10 15 After Sorting: 2 5 5 5 10 15 Polygon Rule: Sum of all smaller sides must be GREATER than the longest side Goal: Find max perimeter where k >= 3 sides n = 6 elements ALGORITHM STEPS 1 Sort Array Ascending order 2 Compute Prefix Sum Track running total 3 Iterate from End Check: sum[0..i-1] > nums[i] 4 Return Max Perimeter First valid = largest Checking from right: i=5: sum=27, nums[5]=15 27>15 OK i=4: sum=17, nums[4]=10 17>10 OK i=3: sum=12, nums[3]=5 12>5 OK Best: All 6 sides = 42 FINAL RESULT Valid 6-sided Polygon: 6 sides 15 10 5 5 5 2 Validation: 2+5+5+5+10 = 27 27 > 15 (longest side) OK Perimeter: 42 2+5+5+5+10+15 = 42 Maximum possible! Key Insight: After sorting, iterate from the largest element backwards. For each position i, check if the prefix sum (sum of elements 0 to i-1) is greater than nums[i]. The first valid position gives the maximum perimeter because we want to include as many (largest) elements as possible. Time: O(n log n), Space: O(1) TutorialsPoint - Find Polygon With the Largest Perimeter | Optimal Solution
Asked in
Amazon 25 Google 18 Facebook 12 Microsoft 8
12.5K Views
Medium Frequency
~25 min Avg. Time
485 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