976. Largest Perimeter Triangle #2226
-
Topics: Given an integer array Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the largest perimeter of a triangle with non-zero area using three lengths from the given array. The key insight is that for three lengths to form a triangle, the sum of the two smaller lengths must be greater than the largest length. Approach
Let's implement this solution in PHP: 976. Largest Perimeter Triangle <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function largestPerimeter($nums) {
rsort($nums);
for ($i = 0; $i < count($nums) - 2; $i++) {
if ($nums[$i + 1] + $nums[$i + 2] > $nums[$i]) {
return $nums[$i] + $nums[$i + 1] + $nums[$i + 2];
}
}
return 0;
}
// Test cases
echo largestPerimeter([2,1,2]) . "\n"; // Output: 5
echo largestPerimeter([1,2,1,10]) . "\n"; // Output: 0
echo largestPerimeter([3,6,2,3]) . "\n"; // Output: 8
?> Explanation:
This approach efficiently narrows down the possible triplets by leveraging sorting and a greedy check, ensuring optimal performance with a time complexity dominated by the sorting step, which is O(n log n). The space complexity is O(1) as no additional space is used beyond the input array. |
Beta Was this translation helpful? Give feedback.
We need to find the largest perimeter of a triangle with non-zero area using three lengths from the given array. The key insight is that for three lengths to form a triangle, the sum of the two smaller lengths must be greater than the largest length.
Approach