https://leetcode.com/problems/largest-perimeter-triangle/
https://leetcode.com/articles/largest-perimeter-triangle/
https://leetcode.com/problems/largest-perimeter-triangle/discuss/217988/JavaC%2B%2BPython-Sort-and-Try-Biggest
Given an array
A
of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths.
If it is impossible to form any triangle of non-zero area, return
0
.
Example 1:
Input: [2,1,2] Output: 5
Example 2:
Input: [1,2,1] Output: 0
Example 3:
Input: [3,2,3,4] Output: 10
Example 4:
Input: [3,6,2,3] Output: 8
Note:
3 <= A.length <= 10000
1 <= A[i] <= 10^6
https://leetcode.com/articles/largest-perimeter-triangle/
https://leetcode.com/problems/largest-perimeter-triangle/discuss/217988/JavaC%2B%2BPython-Sort-and-Try-Biggest
For
a >= b >= c
, a,b,c
can form a triangle if a < b + c
.- We sort the
A
- Try to get a triangle with 3 biggest numbers.
- If
A[n-1] < A[n-2] + A[n-3]
, we get a triangle.
IfA[n-1] >= A[n-2] + A[n-3] >= A[i] + A[j]
, we cannot get any triangle withA[n-1]
- repeat step2 and step3 with the left numbers.
Without loss of generality, say the sidelengths of the triangle are . The necessary and sufficient condition for these lengths to form a triangle of non-zero area is .
Say we knew already. There is no reason not to choose the largest possible and from the array. If , then it forms a triangle, otherwise it doesn't.
Algorithm
This leads to a simple algorithm: Sort the array. For any in the array, we choose the largest possible : these are just the two values adjacent to . If this forms a triangle, we return the answer.
public int largestPerimeter(int[] A) {
Arrays.sort(A);
for (int i = A.length - 3; i >= 0; --i)
if (A[i] + A[i + 1] > A[i + 2])
return A[i] + A[i + 1] + A[i + 2];
return 0;
}