[LeetCode] Find Polygon With the Largest Perimeter

10032. Find Polygon With the Largest Perimeter

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 a1, a2, a3, …, ak where a1 <= a2 <= a3 <= ... <= ak and a1 + a2 + a3 + ... + ak-1 > ak, then there always exists a polygon with k sides whose lengths are a1, a2, a3, …, 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.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
long long largestPerimeter(vector<int>& A) {
sort(begin(A), end(A));
long long res = -1, sum = A[0] + A[1];
for(int i = 2; i < A.size(); i++) {
if(sum > A[i]) res = max(res, sum + A[i]);
sum += A[i];
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/12/24/PS/LeetCode/find-polygon-with-the-largest-perimeter/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.