Leetcode 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
Example 2:
Input: nums = [1,2,1]
Output: 0
nums[i-2]
, nums[i-1]
, and nums[i]
, we only need to check if:
[
nums[i-2] + nums[i-1] > nums[i]
]import java.util.Arrays;
public class LargestPerimeterTriangle {
public int largestPerimeter(int[] nums) {
Arrays.sort(nums);
for (int i = nums.length - 1; i >= 2; i--) {
if (nums[i - 2] + nums[i - 1] > nums[i]) {
return nums[i - 2] + nums[i - 1] + nums[i];
}
}
return 0;
}
public static void main(String[] args) {
LargestPerimeterTriangle lpt = new LargestPerimeterTriangle();
// Test case 1
int[] nums1 = {2, 1, 2};
System.out.println(lpt.largestPerimeter(nums1)); // Output: 5
// Test case 2
int[] nums2 = {1, 2, 1};
System.out.println(lpt.largestPerimeter(nums2)); // Output: 0
}
}
O(n log n)
.O(n)
.Overall, the time complexity is O(n log n)
, which is efficient for the given problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?