LeetCode daily question - day16
If you are new to LeetCode, check in one question every day.
The algorithm may not be very good, but it is just a reflection of my own level. I will make a record of my own questions. Welcome to exchange and learn
(try AC LeetCode’s official daily question)
welcome to exchange and learn!
Topic: 976. Maximum Perimeter of a Triangle
Given an array nums of some positive numbers (representing lengths), return the largest perimeter of a triangle with non-zero area consisting of three of these lengths. Returns 0 if no triangles with non-zero area could be formed.
code:
class Solution {
public:
int largestPerimeter(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(),nums.end());
for(int i = n - 1; i >= 2; i --){
if(nums[i] + nums[i - 1] > nums[ i - 2] && nums[i] - nums[i - 1] < nums[i - 2]){
return nums[i] + nums[i - 1] + nums[i - 2];
}
}
return 0;
}
};