976. Largest Perimeter Triangle LeetCode Solution

In this guide, you will get 976. Largest Perimeter Triangle LeetCode Solution with the best time and space complexity. The solution to Largest Perimeter Triangle problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Largest Perimeter Triangle solution in C++
  4. Largest Perimeter Triangle solution in Java
  5. Largest Perimeter Triangle solution in Python
  6. Additional Resources
976. Largest Perimeter Triangle LeetCode Solution image

Problem Statement of 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

Complexity Analysis

  • Time Complexity: O(\texttt{sort})
  • Space Complexity: O(\texttt{sort})

976. Largest Perimeter Triangle LeetCode Solution in C++

class Solution {
 public:
  int largestPerimeter(vector<int>& nums) {
    ranges::sort(nums);

    for (int i = nums.size() - 1; i > 1; --i)
      if (nums[i - 2] + nums[i - 1] > nums[i])
        return nums[i - 2] + nums[i - 1] + nums[i];

    return 0;
  }
};
/* code provided by PROGIEZ */

976. Largest Perimeter Triangle LeetCode Solution in Java

class Solution {
  public int largestPerimeter(int[] nums) {
    Arrays.sort(nums);

    for (int i = nums.length - 1; i > 1; --i)
      if (nums[i - 2] + nums[i - 1] > nums[i])
        return nums[i - 2] + nums[i - 1] + nums[i];

    return 0;
  }
}
// code provided by PROGIEZ

976. Largest Perimeter Triangle LeetCode Solution in Python

class Solution:
  def largestPerimeter(self, nums: list[int]) -> int:
    nums = sorted(nums)

    for i in range(len(nums) - 1, 1, -1):
      if nums[i - 2] + nums[i - 1] > nums[i]:
        return nums[i - 2] + nums[i - 1] + nums[i]

    return 0
# code by PROGIEZ

Additional Resources

See also  834. Sum of Distances in Tree LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.