notes/OJ notes/pages/Leetcode Largest-Perimeter-Triangle.md
2022-09-03 15:41:36 +08:00

1.4 KiB

Leetcode Largest-Perimeter-Triangle

2022-07-26 08:39

Algorithms:

#algorithm #greedy #math

Difficulty:

#coding_problem #difficulty-easy

Additional tags:

#leetcode

Revisions:

N/A


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

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;
  }
};