Given an array nums of non-negative integers, return the largest perimeter of a triangle with non-zero area that can be formed from three of these lengths.
If it is impossible to form any triangle with non-zero area, return 0.
A triangle is valid if the sum of any two sides is greater than the third side.
3 <= nums.length <= 10^41 <= nums[i] <= 10^6Check every possible combination of three numbers to find the largest perimeter triangle.
Algorithm:
nums[i] + nums[j] > nums[k]nums[i] + nums[k] > nums[j]nums[j] + nums[k] > nums[i]Example Input: nums = [2, 1, 2]
Sorted: [1, 2, 2]
Step-by-step execution:
No other triplets to check.
Result: 5
class SolutionBruteForce {
    public int largestPerimeter(int[] nums) {
        Arrays.sort(nums);
        int max = 0;
        for (int i = 0; i < nums.length - 2; i++) {
            int x = nums[i];
            for (int j = i + 1; j < nums.length - 1; j++) {
                int y = nums[j];
                for (int k = j + 1; k < nums.length; k++) {
                    int z = nums[k];
                    if (x + y > z && x + z > y && y + z > x) {
                        max = Math.max(max, x + y + z);
                    }
                }
            }
        }
        return max;
    }
}
Sort the array and check consecutive triplets starting from the largest numbers.
Algorithm:
nums[i-2] + nums[i-1] > nums[i]Example Input: nums = [2, 1, 2]
Sorted: [1, 2, 2]
Step-by-step execution:
Why this works:
nums[i-2] + nums[i-1] > nums[i] for the largest i, that’s the maximum perimeterclass SolutionOptimized {
    public int largestPerimeter(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        for (int i = n - 1; i >= 2; i--) {
            if (nums[i - 2] + nums[i - 1] > nums[i]) {
                return nums[i] + nums[i - 1] + nums[i - 2];
            }
        }
        return 0;
    }
}
| Approach | Time Complexity | Space Complexity | When to Use | 
|---|---|---|---|
| Brute Force | O(n³) | O(1) | Small arrays (n ≤ 100) | 
| Optimized | O(n log n) | O(1) | Large arrays (n ≤ 10^4) | 
Key Insight: After sorting, the maximum perimeter triangle must include the largest number. We only need to check consecutive triplets starting from the largest numbers.
Triangle Inequality Theorem: For three lengths a ≤ b ≤ c to form a triangle, we need a + b > c.
Greedy Strategy: The optimal triangle will always be among the largest possible numbers that satisfy the triangle inequality.