Skip to content

Commit f17d32e

Browse files
Merge pull request #306 from tiennguyen2310/patch-91
Create LargestPerimeterTriangle.java
2 parents 37af7b2 + e0d5de5 commit f17d32e

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
976. Largest Perimeter Triangle
3+
Solved
4+
Easy
5+
Topics
6+
premium lock icon
7+
Companies
8+
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.
9+
10+
11+
12+
Example 1:
13+
14+
Input: nums = [2,1,2]
15+
Output: 5
16+
Explanation: You can form a triangle with three side lengths: 1, 2, and 2.
17+
Example 2:
18+
19+
Input: nums = [1,2,1,10]
20+
Output: 0
21+
Explanation:
22+
You cannot use the side lengths 1, 1, and 2 to form a triangle.
23+
You cannot use the side lengths 1, 1, and 10 to form a triangle.
24+
You cannot use the side lengths 1, 2, and 10 to form a triangle.
25+
As we cannot use any three side lengths to form a triangle of non-zero area, we return 0.
26+
27+
28+
Constraints:
29+
30+
3 <= nums.length <= 104
31+
1 <= nums[i] <= 106
32+
*/
33+
class Solution {
34+
public int largestPerimeter(int[] nums) {
35+
Arrays.sort(nums);
36+
for(int i = nums.length - 3; i >= 0; i--){
37+
if(nums[i] + nums[i + 1] > nums[i + 2])
38+
return nums[i] + nums[i + 1] + nums[i + 2];
39+
}
40+
return 0;
41+
}
42+
}

0 commit comments

Comments
 (0)