Sunday, January 13, 2019

976. Largest Perimeter Triangle



Version #1 Logical thinking! Math

100.00 %
class Solution {
    public int largestPerimeter(int[] A) {
        // to form a triangle -> a + b > c, b + c > a, c + a > b
        Arrays.sort(A);
        for (int i = A.length - 1; i > 1; i--) {
            // we know that a < b < c
            // -> b + c > a, a + c > b -> are default
            // only need to check if a + b > c
            // given c, b and a are the largest values that we can find, assuming a < b < c
            // if them can't satisfy our requirement, then there's no valid a/b for the current c
            int a = A[i - 2];
            int b = A[i - 1];
            int c = A[i];
            if (a + b > c) {
                return a + b + c;
            }
        }
        return 0;
    }
}

No comments:

Post a Comment