Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created September 28, 2025 17:27
Show Gist options
  • Select an option

  • Save tatsuyax25/d5a124cacb1a6259206ed7f288d6b8ee to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/d5a124cacb1a6259206ed7f288d6b8ee to your computer and use it in GitHub Desktop.
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.
/**
* Finds the largest perimeter of a triangle that can be formed from the given array of side lengths.
* A triangle is valid if the sum of any two sides is greater than the third side.
*
* @param {number[]} nums - Array of positive integers representing side lengths.
* @return {number} - The largest perimeter of a valid triangle, or 0 if none can be formed.
*/
var largestPerimeter = function(nums) {
// Sort the array in descending order to try the largest sides first
nums.sort((a, b) => b - a);
// We only need to check up to the third-to-last element
const n = nums.length - 2;
// Iterate through the sorted array to find the first valid triangle
for (let i = 0; i < n; i++) {
// Check if the current triplet can form a triangle
// Triangle inequality: sum of two smaller sides > largest side
if (nums[i] < nums[i + 1] + nums[i + 2]) {
// If valid, return the perimeter
return nums[i] + nums[i + 1] + nums[i + 2];
}
}
// If no valid triangle is found, return 0
return 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment