Largest Perimeter Triangle — LeetCode 976 Python Solution
- Problem
- #976
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0.
Example
- Input
- nums = [2,1,2]
- Output
- 5
- Explanation
- You can form a triangle with three side lengths: 1, 2, and 2.
Python solution
class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
nums.sort()
for i in range(len(nums) - 1, 1, -1):
if (c := nums[i - 1] + nums[i - 2]) > nums[i]:
return c + nums[i]
return 0Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \log n) |
| Space | O(\log n), where n is the length of the array \textit{nums} auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 976. Largest Perimeter Triangle is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 976. Largest Perimeter Triangle?
- LeetCode 976. Largest Perimeter Triangle is rated Easy on LeetCode.
- What is the time complexity of LeetCode 976. Largest Perimeter Triangle?
- The Python solution on this page runs in O(n \log n).
- What is the space complexity of LeetCode 976. Largest Perimeter Triangle?
- The Python solution on this page uses O(\log n), where n is the length of the array \textit{nums} auxiliary space.
- What topics does LeetCode 976. Largest Perimeter Triangle cover?
- LeetCode 976. Largest Perimeter Triangle is tagged Greedy, Array, Math and Sorting on LeetCode.