2971. Find Polygon With the Largest Perimeter Medium

@problem@discussion
#Array#Greedy#Sorting#Prefix Sum



1/**
2 * [2971] Find Polygon With the Largest Perimeter
3 *
4 * You are given an array of positive integers nums of length n.
5 * 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.
6 * 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.
7 * The perimeter of a polygon is the sum of lengths of its sides.
8 * 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.
9 *  
10 * <strong class="example">Example 1:
11 * 
12 * Input: nums = [5,5,5]
13 * Output: 15
14 * Explanation: The only possible polygon that can be made from nums has 3 sides: 5, 5, and 5. The perimeter is 5 + 5 + 5 = 15.
15 * 
16 * <strong class="example">Example 2:
17 * 
18 * Input: nums = [1,12,1,2,5,50,3]
19 * Output: 12
20 * Explanation: The polygon with the largest perimeter which can be made from nums has 5 sides: 1, 1, 2, 3, and 5. The perimeter is 1 + 1 + 2 + 3 + 5 = 12.
21 * 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.
22 * It can be shown that the largest possible perimeter is 12.
23 * 
24 * <strong class="example">Example 3:
25 * 
26 * Input: nums = [5,5,50]
27 * Output: -1
28 * Explanation: There is no possible way to form a polygon from nums, as a polygon has at least 3 sides and 50 > 5 + 5.
29 * 
30 *  
31 * Constraints:
32 * 
33 * 	3 <= n <= 10^5
34 * 	1 <= nums[i] <= 10^9
35 * 
36 */
37pub struct Solution {}
38
39// problem: https://leetcode.com/problems/find-polygon-with-the-largest-perimeter/
40// discuss: https://leetcode.com/problems/find-polygon-with-the-largest-perimeter/discuss/?currentPage=1&orderBy=most_votes&query=
41
42// submission codes start here
43
44impl Solution {
45    pub fn largest_perimeter(nums: Vec<i32>) -> i64 {
46        
47    }
48}
49
50// submission codes end
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn test_2971() {
58    }
59}
60


Back
© 2025 bowen.ge All Rights Reserved.