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 positive real numbers a1,a2,…,ak with k≥3, a1≤a2≤⋯≤ak and a1+a2+⋯+ak−1>ak, then there always exists a polygon with k sides whose lengths are a1,a2,…,ak.
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.
Function Signature
def largest_perimeter(nums: list[int]) -> int:
Rules
-
Choose any subset of at least 3 elements of
nums
as the sides. Each element can be used at most once, and equal values at different indices count as separate elements.
-
A chosen set of sides is valid only when its largest value is strictly less than the sum of the remaining values. Equality does not form a polygon.
-
The order of
nums
does not matter, and the output is a single number, so it is unique even when several subsets reach the same perimeter.
Constraints
-
3 <= len(nums) <= 10^5
-
1 <= nums[i] <= 10^9
Examples
Input: nums = [5, 5, 5]
Output: 15
The three sides form a triangle because 5 + 5 > 5, and using all of them gives a perimeter of 15.
Input: nums = [1, 12, 1, 2, 5, 50, 3]
Output: 12
Sorted, the values are [1, 1, 2, 3, 5, 12, 50]. 50 cannot be a side because all the other values sum to only 24, and 12 cannot be the longest side because the smaller values sum to 1 + 1 + 2 + 3 + 5 = 12, which is not greater than 12. With 5 as the longest side, 1 + 1 + 2 + 3 = 7 > 5, so the sides [1, 1, 2, 3, 5] give a perimeter of 12.
Input: nums = [5, 5, 50]
Output: -1
A polygon needs all three elements here, and 5 + 5 = 10 is not greater than 50.