Largest Perimeter Triangle in O(NLogN)
Problem is this: https://leetcode.com/problems/largest-perimeter-triangle/description/
Remember that for a triangle to be valid with Area > 0, the following condition must be true:
Side1 + Side2 > Side3
Notice that you can't use greater than or equal since the equal means area = 0. The solution becomes straightforward if you sort the array: from largest to smallest, find the first triplet matching the aforementioned condition, and then you're done. Hence O(NLogN) in 4 lines of code. Thanks! A.C.C.
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
Remember that for a triangle to be valid with Area > 0, the following condition must be true:
Side1 + Side2 > Side3
Notice that you can't use greater than or equal since the equal means area = 0. The solution becomes straightforward if you sort the array: from largest to smallest, find the first triplet matching the aforementioned condition, and then you're done. Hence O(NLogN) in 4 lines of code. Thanks! A.C.C.
public class Solution
{
public int LargestPerimeter(int[] A)
{
if (A == null || A.Length < 3) return 0;
Array.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;
}
}
Cannot get any more elegant :) My C++ solution is almost identical:
ReplyDeleteclass Solution {
public:
int largestPerimeter(vector& A) {
sort(A.begin(), A.end());
for (int i = A.size()-1; i >= 2; --i) {
if (A[i] < A[i-1] + A[i-2]) return A[i] + A[i-1] + A[i-2];
}
return 0;
}
};