Skip to main content
Back to problems
#976
Easy Algorithms

Largest perimeter triangle

Array Math Greedy Sorting
62.0% acceptance
Feb 25, 2026
3393
443
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn largest_perimeter(mut nums: Vec<i32>) -> i32 {
    nums.sort_unstable_by(|a, b| b.cmp(a));
    for i in 0..nums.len()-2 {
      if nums[i] < nums[i+1] + nums[i+2] {
        return nums[i] + nums[i+1] + nums[i+2];
      }
    }
    0
  }
}