Algorithm


Problem Name: 976. Largest Perimeter Triangle

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.

 

Example 1:

Input: nums = [2,1,2]
Output: 5
Explanation: You can form a triangle with three side lengths: 1, 2, and 2.

Example 2:

Input: nums = [1,2,1,10]
Output: 0
Explanation: 
You cannot use the side lengths 1, 1, and 2 to form a triangle.
You cannot use the side lengths 1, 1, and 10 to form a triangle.
You cannot use the side lengths 1, 2, and 10 to form a triangle.
As we cannot use any three side lengths to form a triangle of non-zero area, we return 0.

 

Constraints:

  • 3 <= nums.length <= 104
  • 1 <= nums[i] <= 106

Code Examples

#1 Code Example with Java Programming

Code - Java Programming


class Solution {
  public int largestPerimeter(int[] nums) {
    Arrays.sort(nums);
    for (int i = nums.length - 3; i >= 0; i--) {
      if (nums[i] + nums[i + 1] > nums[i + 2]) {
        return nums[i] + nums[i + 1] + nums[i + 2];
      }
    }
    return 0;
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [2,1,2]

Output

x
+
cmd
5

#2 Code Example with Javascript Programming

Code - Javascript Programming


const largestPerimeter = function(nums) {
  nums.sort((a, b) => a - b)
  for(let i = nums.length - 1; i > 1; i--) {
    if(nums[i] < nums[i - 1] + nums[i - 2]> return nums[i - 2] + nums[i - 1] + nums[i]
  }
  return 0
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [2,1,2]

Output

x
+
cmd
5

#3 Code Example with Python Programming

Code - Python Programming


class Solution:
    def largestPerimeter(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        A.sort()
        return ([0] + [a + b + c for a, b, c in zip(A, A[1:], A[2:]) if c < a + b])[-1]
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [1,2,1,10]

#4 Code Example with C# Programming

Code - C# Programming


using System;

namespace LeetCode
{
    public class _0976_LargestPerimeterTriangle
    {
        public int LargestPerimeter(int[] A)
        {
            Array.Sort(A);
            for (int i = A.Length - 3; i >= 0; i--)
            {
                if (A[i] + A[i + 1] > A[i + 2])
                    return A[i] + A[i + 1] + A[i + 2];
            }

            return 0;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [1,2,1,10]
Advertisements

Demonstration


Previous
#975 Leetcode Odd Even Jump Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#977 Leetcode Squares of a Sorted Array Solution in C, C++, Java, JavaScript, Python, C# Leetcode