[LeetCode] Largest Perimeter Triangle

976. Largest Perimeter Triangle

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int largestPerimeter(vector<int>& nums) {
sort(nums.begin(),nums.end());
int res = 0, l = 0, r = nums.size() - 1;
for(int i = nums.size() - 1; i >= 2; i--) {
//nums[l] + nums[m] > nums[r]
if(nums[i-2] + nums[i-1] > nums[i]) {
return nums[i-2]+nums[i-1]+nums[i];
}
}

return 0;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/27/PS/LeetCode/largest-perimeter-triangle/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.