LeetCode—976

Approach

# 數學題,三角形的邊滿足 a - b < x < a + b
Three sides of the triangle satisfy rule : a - b < x < a + b

# 先排序,再從數字大找到小並剔除掉不會形成三角形的可能性
First sort the numbers, then check them from largest to smallest and eliminate any combination that cannot form a triangle.

Time Complexity

# n = length of nums, sort time complexity is nlogn.
O(nlogn) 

Space Complexity

# n = 1
O(1)

Code

class Solution {
public:
    int largestPerimeter(vector<int>& nums) {
        int ans = 0;

        sort(nums.begin(), nums.end());

        for (int i = nums.size() - 1 ; i >= 2 ; i--) {
            if (nums[i - 1] + nums[i - 2] > nums[i]) {
                ans = nums[i] + nums[i - 1] + nums[i - 2];
                break;
            }
        }

        return ans;
    }
};