2022-07-26 08:45:09 +08:00
# Leetcode Largest-Perimeter-Triangle
#### 2022-07-26 08:39
> ##### Algorithms:
2022-09-03 15:41:36 +08:00
>
2022-07-26 08:56:08 +08:00
> #algorithm #greedy #math
2022-09-03 15:41:36 +08:00
>
2022-07-26 08:45:09 +08:00
> ##### Difficulty:
2022-09-03 15:41:36 +08:00
>
2022-07-26 08:45:09 +08:00
> #coding_problem #difficulty-easy
2022-09-03 15:41:36 +08:00
>
2022-07-26 08:45:09 +08:00
> ##### Additional tags:
2022-09-03 15:41:36 +08:00
>
> #leetcode
>
2022-07-26 08:45:09 +08:00
> ##### Revisions:
2022-09-03 15:41:36 +08:00
>
2022-07-26 08:45:09 +08:00
> N/A
##### Related topics:
2022-09-03 15:41:36 +08:00
2022-07-26 08:45:09 +08:00
##### Links:
2022-09-03 15:41:36 +08:00
2022-07-26 08:56:08 +08:00
- [Link to problem ](https://leetcode.com/problems/largest-perimeter-triangle/ )
2022-09-03 15:41:36 +08:00
---
2022-07-26 08:45:09 +08:00
### Problem
2022-07-26 08:56:08 +08:00
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` .
2022-07-26 08:45:09 +08:00
#### Examples
2022-07-26 08:56:08 +08:00
**Example 1:**
**Input:** nums = [2,1,2]
**Output:** 5
**Example 2:**
**Input:** nums = [1,2,1]
**Output:** 0
2022-07-26 08:45:09 +08:00
#### Constraints
2022-09-03 15:41:36 +08:00
- `3 <= nums.length <= 104`
- `1 <= nums[i] <= 106`
2022-07-26 08:56:08 +08:00
2022-07-26 08:45:09 +08:00
### Thoughts
> [!summary]
2022-07-26 08:56:08 +08:00
> This is a #math problem.
After sorting, the answer must be consecutive 3 elements.
#### Why?
assume l, m , r.
if nums[l] + nums[m] < nums [ r ] , because after sorting ,
the order is ascending, anything before l and m will not suffice.
2022-07-26 08:45:09 +08:00
### Solution
2022-07-26 08:56:08 +08:00
```cpp
class Solution {
public:
int largestPerimeter(vector< int > & nums) {
sort(nums.begin(), nums.end());
int r = nums.size() - 1;
// change l first until its boundary
for (int i = r; i > 1; i--) {
if (nums[i] < nums [ i - 1 ] + nums [ i - 2 ] ) {
return nums[i] + nums[i - 1] + nums[i - 2];
}
}
return 0;
}
};
2022-09-03 15:41:36 +08:00
```