Given an array
A
of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths.javaIf it is impossible to form any triangle of non-zero area, return
0
.ide
Example 1:spa
Input: [2,1,2] Output: 5
Example 2:code
Input: [1,2,1] Output: 0
Example 3:orm
Input: [3,2,3,4] Output: 10
Example 4:blog
Input: [3,6,2,3] Output: 8
Note:three
3 <= A.length <= 10000
1 <= A[i] <= 10^6
Approach #1: Math. [Java]input
class Solution { public int largestPerimeter(int[] A) { Arrays.sort(A); int n = A.length; // Integer[] arr = new Integer[A.length]; // for (int i = 0; i < A.length; ++i) // arr[i] = A[i]; // Arrays.sort(A, new Comparator<Integer>() { // @Override // public int compare(Integer a, Integer b) { // return b - a; // } // }); // Arrays.sort(arr, (Integer a, Integer b) -> b - a); // Arrays.sort(arr, Collections.reverseOrder()); for (int i = n - 1; i >= 0; --i) { for (int j = i - 1; j >= 0; --j) { for (int k = j - 1; k >= 0; --k) { if (A[k] + A[j] > A[i]) { return A[k] + A[j] + A[i]; } } } } return 0; } }
Analysis:it
There three ways to realise reverse array, but the permise is that array's type must is object. so we have to change the type of A, If we do so, it will TEL. io
Approach #2: Math. [Java]
class Solution { public int largestPerimeter(int[] A) { int c = max(A); int b = max(A); int a = max(A); for(int i = 2; i < A.length; i++) { if(c < a + b) return a + b + c; else { c = b; b = a; a = max(A); } } return 0; } int max(int[] A) { int m = A[0]; int index = 0; for(int i = 1; i < A.length; i++) { if(A[i] > m) { m = A[i]; index = i; } } A[index] = -1; return m; } }