976. Largest Perimeter Triangle(Solution || Leetcode easy || Java)

Palakkgoyal
1 min readNov 15, 2022

--

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

Example 2:

Input: nums = [1,2,1]
Output: 0

Constraints:

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

SOLUTION:

class Solution {
public int largestPerimeter(int[] nums) {
//first we are going to sort the array
Arrays.sort(nums);

//if the sum of elements is greater than the largest element
// then that trio is our answer, as if the sum is less than
//the largest element then that trio will not be able to form
// a triangle
for(int i = nums.length - 1; i > 1; i--){
if(nums[i-1] + nums[i-2] > nums[i]){
return nums[i-1]+nums[i-2]+nums[i];
}
}

return 0;//if you do not find any such triplet return 0;
}
}

Thank you for reading. If you have any queries then, please let me know in the comment section. I will surely be responsive toward it.

--

--

Palakkgoyal
Palakkgoyal

Written by Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

No responses yet