vault backup: 2022-07-26 08:56:08

This commit is contained in:
juan 2022-07-26 08:56:08 +08:00
parent 753517fa96
commit fdb29cf0ca
2 changed files with 48 additions and 4 deletions

View file

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

View file