All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0901_1000.s0976_largest_perimeter_triangle.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0901_1000.s0976_largest_perimeter_triangle;

// #Easy #Array #Math #Sorting #Greedy #Programming_Skills_I_Day_3_Conditional_Statements
// #2022_03_31_Time_12_ms_(26.01%)_Space_53.8_MB_(69.91%)

import java.util.Arrays;

/**
 * 976 - Largest Perimeter Triangle\.
 *
 * Easy
 *
 * Given an integer array `nums`, return _the largest perimeter of a triangle with a non-zero area, formed from three of these lengths_. If it is impossible to form any triangle of a non-zero area, return `0`.
 *
 * **Example 1:**
 *
 * **Input:** nums = [2,1,2]
 *
 * **Output:** 5
 *
 * **Example 2:**
 *
 * **Input:** nums = [1,2,1]
 *
 * **Output:** 0
 *
 * **Constraints:**
 *
 * *   3 <= nums.length <= 104
 * *   1 <= nums[i] <= 106
**/
public class Solution {
    public int largestPerimeter(int[] nums) {
        // for non zero area of triangle (c < a+b)
        Arrays.sort(nums);
        for (int i = nums.length - 1; i >= 2; i--) {
            if (nums[i] < nums[i - 1] + nums[i - 2]) {
                return nums[i] + nums[i - 1] + nums[i - 2];
            }
        }
        return 0;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy