Find Polygon With the Largest Perimeter — LeetCode 2971 Python Solution

MediumGreedyArrayPrefix SumSorting
Problem
#2971
Pattern
Prefix Sum
Reading time
2 min

The problem

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.

Example

Input
nums = [5,5,5]
Output
15
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.

Python solution

Python
class Solution:
    def largestPerimeter(self, nums: List[int]) -> int:
        nums.sort()
        s = list(accumulate(nums, initial=0))
        ans = -1
        for k in range(3, len(nums) + 1):
            if s[k - 1] > nums[k - 1]:
                ans = max(ans, s[k])
        return ans

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2971. Find Polygon With the Largest Perimeter is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2971. Find Polygon With the Largest Perimeter?
LeetCode 2971. Find Polygon With the Largest Perimeter is rated Medium on LeetCode.
What topics does LeetCode 2971. Find Polygon With the Largest Perimeter cover?
LeetCode 2971. Find Polygon With the Largest Perimeter is tagged Greedy, Array, Prefix Sum and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview