notes/OJ notes/pages/Leetcode Largest-Perimeter-Triangle.md

79 lines
1.4 KiB
Markdown
Raw Normal View History

2022-07-26 08:45:09 +08:00
# Leetcode Largest-Perimeter-Triangle
#### 2022-07-26 08:39
> ##### Algorithms:
2022-07-26 08:56:08 +08:00
> #algorithm #greedy #math
2022-07-26 08:45:09 +08:00
> ##### Difficulty:
> #coding_problem #difficulty-easy
> ##### Additional tags:
> #leetcode
> ##### Revisions:
> N/A
##### Related topics:
```expander
2022-07-26 08:56:08 +08:00
tag:#math
2022-07-26 08:45:09 +08:00
```
##### Links:
2022-07-26 08:56:08 +08:00
- [Link to problem](https://leetcode.com/problems/largest-perimeter-triangle/)
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-07-26 08:56:08 +08:00
- `3 <= nums.length <= 104`
- `1 <= nums[i] <= 106`
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;
}
};
```