[LeetCode Daily Question] [Simple] 976. The maximum perimeter of a triangle

[LeetCode Daily Question] [Simple] 976. The maximum perimeter of a triangle

976. Maximum perimeter of a triangle

976. Maximum perimeter of a triangle

Algorithm idea: array

topic:

Insert picture description here

java code

O(nlogn) method:

  1. Sort the edges in ascending order;
  2. Search from large to small, if edge[i], edge[i+1], edge[i+2] can form a triangle, that is, a triangle with a large perimeter;

Reason:
Triangle condition: A<B+C (where A is the longest side);
to make the perimeter the longest, B+C should be as large as possible;
after sorting, the remaining sides of B+C should be the largest, if not If it is satisfied, there is no edge that can satisfy B+C>A, that is, for A, there is no triangle; if it is satisfied, it is the triangle with the largest circumference;

class Solution {
    
    
    public int largestPerimeter(int[] A) {
    
    
		Arrays.sort(A);//排序(正序)
		int n = A.length;
		for (int i = n-1; i > 1; i--) {
    
    //从后向前,
			if (A[i] < A[i-1] + A[i-2]) {
    
    //成立,存在三角形
				return A[i] + A[i-1] + A[i-2];
			}
		}
		return 0;
    }
}

Guess you like

Origin blog.csdn.net/qq_39457586/article/details/110310844