Skip to main content
impol.dev

Editorial

Solution walkthrough

Review the explanation, then compare the reference implementation.

Video explanation

Solution

Intuition

For a fixed largest side, the two largest available smaller sides maximize both their sum and the perimeter. If even those two fail the triangle inequality, no pair can form a triangle with that largest side. This supports scanning candidate triples from largest to smallest.

Approach

Sort the lengths. For each index k from right to left, test whether nums[k - 2] + nums[k - 1] > nums[k]. Return their total at the first success. All triples using a previously rejected largest side are impossible, while every triple using a smaller largest side has no greater perimeter than the current top-three choice. Return zero if no nondegenerate triangle exists.

class Solution: def largestPerimeter(self, nums: List[int]) -> int: nums.sort() for k in range(len(nums) - 1, 1, -1): curr = nums[k - 2] + nums[k - 1] if curr > nums[k]: return curr + nums[k] return 0

Complexity analysis

For n side lengths, sorting costs O(n log n) and the descending scan costs O(n), so total time is O(n log n). Auxiliary space is O(1) for the scan; language sort workspace is implementation-dependent and can be O(n).