g0901_1000.s0976_largest_perimeter_triangle.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0901_1000.s0976_largest_perimeter_triangle;
// #Easy #Array #Math #Sorting #Greedy #Programming_Skills_I_Day_3_Conditional_Statements
// #2022_03_31_Time_12_ms_(26.01%)_Space_53.8_MB_(69.91%)
import java.util.Arrays;
/**
* 976 - Largest Perimeter Triangle\.
*
* Easy
*
* 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
**/
public class Solution {
public int largestPerimeter(int[] nums) {
// for non zero area of triangle (c < a+b)
Arrays.sort(nums);
for (int i = nums.length - 1; i >= 2; i--) {
if (nums[i] < nums[i - 1] + nums[i - 2]) {
return nums[i] + nums[i - 1] + nums[i - 2];
}
}
return 0;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy