notes/OJ notes/pages/Leetcode Largest-Perimeter-Triangle.md
2022-07-26 08:56:08 +08:00

79 lines
1.4 KiB
Markdown

# Leetcode Largest-Perimeter-Triangle
#### 2022-07-26 08:39
> ##### Algorithms:
> #algorithm #greedy #math
> ##### Difficulty:
> #coding_problem #difficulty-easy
> ##### Additional tags:
> #leetcode
> ##### Revisions:
> N/A
##### Related topics:
```expander
tag:#math
```
##### Links:
- [Link to problem](https://leetcode.com/problems/largest-perimeter-triangle/)
___
### Problem
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`.
#### Examples
**Example 1:**
**Input:** nums = [2,1,2]
**Output:** 5
**Example 2:**
**Input:** nums = [1,2,1]
**Output:** 0
#### Constraints
- `3 <= nums.length <= 104`
- `1 <= nums[i] <= 106`
### Thoughts
> [!summary]
> 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.
### Solution
```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;
}
};
```