From fdb29cf0ca8cdb532887965e0824b8a36869f04b Mon Sep 17 00:00:00 2001 From: juan Date: Tue, 26 Jul 2022 08:56:08 +0800 Subject: [PATCH] vault backup: 2022-07-26 08:56:08 --- .../Leetcode Largest-Perimeter-Triangle.md | 52 +++++++++++++++++-- OJ notes/pages/Untitled.md | 0 2 files changed, 48 insertions(+), 4 deletions(-) create mode 100644 OJ notes/pages/Untitled.md diff --git a/OJ notes/pages/Leetcode Largest-Perimeter-Triangle.md b/OJ notes/pages/Leetcode Largest-Perimeter-Triangle.md index 410e3ee..a57d05f 100644 --- a/OJ notes/pages/Leetcode Largest-Perimeter-Triangle.md +++ b/OJ notes/pages/Leetcode Largest-Perimeter-Triangle.md @@ -3,7 +3,7 @@ #### 2022-07-26 08:39 > ##### Algorithms: -> #algorithm #greedy +> #algorithm #greedy #math > ##### Difficulty: > #coding_problem #difficulty-easy > ##### Additional tags: @@ -13,23 +13,67 @@ ##### Related topics: ```expander -tag:# +tag:#math ``` ##### Links: -- [Link to problem]() +- [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 #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 + +```cpp +class Solution { +public: + int largestPerimeter(vector &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; + } +}; +``` \ No newline at end of file diff --git a/OJ notes/pages/Untitled.md b/OJ notes/pages/Untitled.md new file mode 100644 index 0000000..e69de29