⚡Flashcard Drill➔
NeetCode #150LC-2971MediumArrays & Hashing
← Back to All Problems

#150 · #2971 · Find Polygon With the Largest Perimeter(找到最大周长的多边形)

📌 Problem Statement & Constraints

Given an array nums of positive integers, return the largest perimeter of a polygon with at least 3 sides that can be formed from a subset of nums, or -1 if impossible. Constraints: 3 <= nums.length <= 10^5, 1 <= nums[i] <= 10^9.

💡 Core Algorithmic Approaches

  1. The polygon inequality for a sorted set of side lengths is that the largest side must be strictly less than the sum of the others.
  2. If a sorted array satisfies this for some index i, then using the prefix nums[0..i] maximises the perimeter among all valid subsets ending at i.
  3. So sort the array and scan from the largest index downward: the first index where nums[i] < sum(nums[0..i-1]) gives the answer sum(nums[0..i]).
  4. Scanning from the largest index guarantees the maximum perimeter, since the perimeter is the prefix sum.

💻 Benchmark Python3 Implementation

class Solution:
    def largestPerimeter(self, nums: List[int]) -> int:
        nums.sort()
        n = len(nums)
        pref = [0] * (n + 1)
        for i, x in enumerate(nums):
            pref[i + 1] = pref[i] + x
        for i in range(n - 1, 1, -1):      # at least 3 sides
            if nums[i] < pref[i]:          # largest < sum of the rest
                return pref[i + 1]
        return -1

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n log n): the sort dominates; the scan is O(n).
💾 Space Complexity
O(n) for the prefix array (O(1) extra with a running total).

⚠️ Interview Pitfalls & Follow-ups

  • Using <= instead of <: the polygon inequality is strict; a degenerate triangle where the largest equals the sum of the others has zero area and is invalid.
  • Requiring exactly 3 sides: the problem allows any number of sides, so a longer prefix may give a larger perimeter.
  • Scanning from the smallest index: that would return the smallest valid perimeter, not the largest.
  • Forgetting the i >= 2 bound: a polygon needs at least 3 sides.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

找到最大周长的多边形

给你一个长度为 n 的整数数组 nums,它表示一个 n 条边的多边形的边长。请从中选出一个或多个边(至少 3 条),使得它们能组成一个面积不为零的多边形,并返回这个多边形的 最大周长 。如果无法组成任何多边形,返回 −1。约束:3 ≤ nums.length ≤ 10^5;1 ≤ nums[i] ≤ 10^9。

核心要点

  • 多边形不等式(核心) :一组边能构成多边形的充要条件是「最长边 &lt; 其余边之和」。
  • 排序后从大到小尝试(标准解) :把 nums 升序排序。从最大的元素开始,检查「它是否是所选边中最长的,且剩余边之和大于它」。
  • 贪心策略 :对排序后的数组,从右往左找到第一个满足 sum(nums[0..i-1]) &gt; nums[i] 的 i,则 sum(nums[0..i]) 即为最大周长。
  • 为什么这样能得到最大周长 :若以 nums[i] 为最长边可行,那么包含 nums[i] 及所有更小边的集合周长最大。由于 nums 升序, sum(nums[0..i]) 随 i 增大而增大,因此第一个满足条件的 i 对应最大周长。

常见陷阱

  • 条件写成 &gt;= :多边形不等式是 严格 的——最长边必须 小于 其余边之和。相等时三条边会退化成一条直线(面积为 0),不构成多边形。
  • 从小往大找 :应 从大到小 找,因为要最大化周长。从小到大找到的第一个可行集合周长较小。
  • 忘记至少 3 条边 :循环必须保证剩余边数 ≥ 3,因此 range(len(nums)-1, 1, -1) 的下界是 2(下标),对应 3 条边。
  • 每次重新求 sum(nums[:i]) :O(n²)。必须用「total 递减」的方式增量维护。

参考实现

class Solution:
    def largestPerimeter(self, nums: list[int]) -> int:
        nums.sort()
        total = sum(nums)                       # 初始为「全部元素之和」
        for i in range(len(nums) - 1, 1, -1):   # 至少保留 3 条边
            if total - nums[i] > nums[i]:       # 其余边之和 > 最长边
                return total
            total -= nums[i]                    # 该边不能作为最长边,移除
        return -1