#2971

Find Polygon With the Largest Perimeter

Medium
ArrayGreedySortingPrefix SumGreedySorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

By sorting the array and checking the largest sides first, we can quickly determine if a valid polygon can be formed. This is efficient because it reduces the number of checks needed.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the array in non-decreasing order.
  2. 2Step 2: Iterate from the end of the sorted array to the beginning, checking sets of three consecutive sides.
  3. 3Step 3: If the longest side is less than the sum of the other two sides, return the perimeter of these three sides.
  4. 4Step 4: If no valid sides are found, return -1.
solution.py6 lines
1def largestPerimeter(nums):
2    nums.sort()
3    for i in range(len(nums) - 1, 1, -1):
4        if nums[i] < nums[i - 1] + nums[i - 2]:
5            return nums[i] + nums[i - 1] + nums[i - 2]
6    return -1

Complexity note: The complexity is O(n log n) due to the sorting step, which is efficient for the input size constraints.

  • 1Sorting helps to quickly identify valid sides for a polygon.
  • 2The triangle inequality principle is crucial for determining valid polygons.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.