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
.
nums
?
nums.length
would range from 3 to 10^4.nums
guaranteed to be positive integers?
nums
consists of positive integers.0
since it’s impossible to form a triangle.To form a valid triangle with sides a
, b
, and c
(where a <= b <= c
), the triangle inequality theorem states that a + b > c
. The goal is to find the largest possible perimeter under this constraint.
Sorting: Start by sorting the array in descending order to maximize the perimeter. Consider the first three elements and check if they can form a triangle.
Greedy Approach: Iterate over the sorted list, always checking the first three elements that haven’t been ruled out. If they satisfy the triangle condition, their sum is the maximum possible perimeter.
Early Termination: Once a valid triangle is found, return its perimeter immediately since sorting in descending order ensures maximum perimeter is considered first.
def largestPerimeter(nums):
# Sort the numbers in descending order
nums.sort(reverse=True)
# Check each triplet of consecutive elements
for i in range(len(nums) - 2):
if nums[i] < nums[i + 1] + nums[i + 2]:
# Found a valid triangle, return its perimeter
return nums[i] + nums[i + 1] + nums[i + 2]
# No valid triangle found
return 0
n
is the length of nums
.Overall, the time complexity of the solution is O(n log n) due to the sorting step. The subsequent scan is linear and thus does not affect the leading term.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?