题目来源于力扣(LeetCode)
题目相关标签:排序、数学

提示:
3 <= A.length <= 10000
1 <= A[i] <= 10^6
首先对数组进行排序
倒序遍历数组,对范围内的数组元素进行比较
判断当前遍历的元素是否小于前两位元素的和
三角形定理:任意两条边大于第三条边
即判断较小的两条边的和是否大于较长的一条边
public static int largestPerimeter(int[] A) {
    int[] nums = A;
    // 排序操作
    Arrays.sort(nums);
    // 倒序遍历
    for (int i = nums.length - 1; i >= 2; i--) {
        int a = nums[i];
        int b = nums[i - 1];
        int c = nums[i - 2];
        // 三角形的任意两条边都大于另一条边
        if (a < b + c) {
            return a + b + c;
        }
    }
    return 0;
}

public static void main(String[] args) {
    int[] nums = {2, 1, 2};  // output: 5
//    int[] nums = {1, 2, 1};  // output: 0
//    int[] nums = {3, 2, 3, 4};  // output: 10
//    int[] nums = {3, 6, 2, 3};  // output: 8
    int result = largestPerimeter(nums);
    System.out.println(result);
}
原文:https://www.cnblogs.com/zhiyin1209/p/13184304.html