Leetcode 976. Largest Perimeter Triangle
Given an array of positive integers 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
Array: What is the range of values for the length of the array nums
?
nums
will be between 3 and 10,000.nums
: What is the range of each element in nums
?
nums
will be a positive integer less than or equal to 10^6
.nums
array?
nums
array in non-decreasing order.a
, b
, and c
, the sum of any two sides must be greater than the third side.a ≤ b ≤ c
, then a + b > c
must hold to form a triangle.0
.O(n log n)
.O(n)
in the worst case.O(n log n)
due to the sorting step.#include <vector>
#include <algorithm>
class Solution {
public:
int largestPerimeter(std::vector<int>& nums) {
std::sort(nums.begin(), nums.end());
for (int i = nums.size() - 1; i >= 2; --i) {
if (nums[i-1] + nums[i-2] > nums[i]) {
return nums[i] + nums[i-1] + nums[i-2];
}
}
return 0;
}
};
nums
is sorted in non-decreasing order.i
from the end of the sorted array), check if the largest side can form a triangle with the two preceding sides. The check nums[i-1] + nums[i-2] > nums[i]
ensures the triangle inequality theorem is satisfied.0
.This approach ensures that we get the largest perimeter triangle efficiently.
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?