Find Polygon with the Largest Perimeter

Medium Topics Company Tags

Choose at least three entries of nums as side lengths of a polygon. Such a polygon exists exactly when its longest side is strictly shorter than the sum of all other chosen sides. Return the largest possible sum of chosen side lengths, or -1 if no polygon can be formed.

Example 1:

Input: nums = [2,3,4]

Output: 9

Explanation: Use all three sides. The longest side, 4, is smaller than 2 + 3, so the perimeter is 2 + 3 + 4 = 9.

Example 2:

Input: nums = [1,2,3]

Output: -1

Explanation: The longest side equals 1 + 2, but the inequality must be strict. With only three available entries, no polygon is possible.

Example 3:

Input: nums = [3,3,3,20]

Output: 9

Explanation: The side of length 20 exceeds the sum of the other sides, so it cannot be used. The three sides of length 3 form a polygon with perimeter 9.

Constraints:

  • 3 <= nums.length <= 100000
  • 1 <= nums[i] <= 1000000000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.