976. Largest Perimeter Triangle
Written by Ron on 010111 April 000112011. Posted in Blog
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 1:
Input: nums = [2,1,2]
Output: 5
Example 2:
Input: nums = [1,2,1]
Output: 0
Constraints:
3 <= nums.length <= 104
1 <= nums[i] <= 106
from typing import List
class Solution:
def largestPerimeter(self, nums: List[int]) -> int:
_len = len(nums)
nums.sort()
for i in range(_len-1, 1, -1): #range(start, stop, step)
if nums[i] < nums[i-1] + nums[i-2]:
return nums[i] + nums[i-1] + nums[i-2]
return 0
s = Solution()
print(s.largestPerimeter([3,2,2,1,1,3,1]))#8
print(s.largestPerimeter([3,2,3,4]))#10
print(s.largestPerimeter([2,1,2]))#5
print(s.largestPerimeter([1,2,1]))#0