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 <= ... <= akanda1 + 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 thelargest possible perimeter of a polygon whose sides can be formed fromnums, or-1if it is not possible to create a polygon.
Input: nums =[1,12,1,2,5,50,3]Output: 12Explanation: The polygon with the largest perimeter which can be made from nums has 5 sides:1,1,2,3, and 5. The perimeter is1+1+2+3+5=12.We cannot have a polygon with either 12 or 50 as the longest side because it is not possible to include 2 or more smaller sides that have a greater sum than either of them.It can be shown that the largest possible perimeter is12.
To form a polygon, the sum of all sides except the largest must be greater than the largest side. To maximize the perimeter, we sort the array and try to use as many largest sides as possible, checking the polygon condition from the largest possible subset down to 3 sides.
classSolution {
publiclonglargestPerimeter(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
long[] pre =newlong[n+1];
for (int i = 0; i < n; i++) pre[i+1]= pre[i]+ nums[i];
for (int k = n; k >= 3; k--) {
if (pre[k-1]> nums[k-1]) return pre[k];
}
return-1;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funlargestPerimeter(nums: IntArray): Long {
nums.sort()
val n = nums.size
val pre = LongArray(n+1)
for (i in0 until n) pre[i+1] = pre[i] + nums[i]
for (k in n downTo 3) {
if (pre[k-1] > nums[k-1]) return pre[k]
}
return -1 }
}
1
2
3
4
5
6
7
8
9
10
classSolution:
deflargestPerimeter(self, nums: list[int]) -> int:
nums.sort()
pre = [0]
for x in nums:
pre.append(pre[-1] + x)
for k in range(len(nums), 2, -1):
if pre[k-1] > nums[k-1]:
return pre[k]
return-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnlargest_perimeter(nums: Vec<i32>) -> i64 {
letmut nums = nums;
nums.sort();
let n = nums.len();
letmut pre =vec![0i64; n+1];
for i in0..n {
pre[i+1] = pre[i] + nums[i] asi64;
}
for k in (3..=n).rev() {
if pre[k-1] > nums[k-1] asi64 {
return pre[k];
}
}
-1 }
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
largestPerimeter(nums: number[]):number {
nums.sort((a, b) =>a-b);
constn=nums.length;
constpre: number[] = [0];
for (leti=0; i<n; i++) pre.push(pre[pre.length-1] +nums[i]);
for (letk=n; k>=3; k--) {
if (pre[k-1] >nums[k-1]) returnpre[k];
}
return-1;
}
}