Leetcode 2971: Find Polygon With the Largest Perimeter

grid47
grid47
Exploring patterns and algorithms
Jan 14, 2024 6 min read

You are given an array nums consisting of positive integers. A polygon can be formed from the integers if it satisfies the following condition: the sum of the lengths of any k-1 sides must be greater than the length of the remaining side. The perimeter of a polygon is the sum of the lengths of its sides. Your task is to find the largest possible perimeter of a polygon that can be formed using the sides from nums, or return -1 if it is not possible to form such a polygon.
Problem
Approach
Steps
Complexity
Input: The input consists of an array `nums` of positive integers. The task is to determine the largest possible perimeter of a polygon that can be made from the elements in `nums`.
Example: nums = [4, 6, 7, 3]
Constraints:
• 3 <= n <= 10^5
• 1 <= nums[i] <= 10^9
Output: Return the largest possible perimeter of a polygon that can be formed using the elements in `nums`, or return `-1` if no valid polygon can be made.
Example: Output: 17
Constraints:
Goal: The goal is to find the largest possible perimeter of a polygon formed by the sides in `nums`. The key condition is that the sum of the lengths of any `k-1` sides must be greater than the length of the remaining side.
Steps:
• Sort the array `nums` in ascending order.
• Iterate through the array from the largest element and check if the sum of all elements smaller than the current element is greater than the current element.
• If the condition is met, return the sum of the elements that form the polygon (perimeter).
• If no valid polygon can be formed, return -1.
Goal: The array has at least three integers, and the values of `nums[i]` range from 1 to 10^9. The task is to determine the largest possible perimeter from the elements in `nums`.
Steps:
• 3 <= n <= 10^5
• 1 <= nums[i] <= 10^9
Assumptions:
• The array is guaranteed to have at least three integers, as this is a requirement for forming a polygon.
• All elements in the array are positive integers.
Input: Input: nums = [4, 6, 7, 3]
Explanation: The array is sorted as [3, 4, 6, 7]. We can form a polygon with sides 3, 4, 6, and 7. The sum of the sides is 17, which is the largest perimeter that can be formed.

Input: Input: nums = [8, 10, 2, 1, 5, 7]
Explanation: The sorted array is [1, 2, 5, 7, 8, 10]. A polygon can be formed with sides 1, 2, 5, 7, and 10. The perimeter is 25.

Input: Input: nums = [10, 20, 30]
Explanation: The sorted array is [10, 20, 30]. We cannot form a polygon because the longest side 30 is greater than the sum of the other two sides (10 + 20).

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus