LeetCode Entry

976. Largest Perimeter Triangle

28.09.2025 easy 2025 kotlin rust

Max triangle perimeter from array of lengths window

976. Largest Perimeter Triangle easy blog post substack youtube

1.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1126

Problem TLDR

Max triangle perimeter from array of lengths #easy #sliding_window

Intuition

Sort. Consider every 3-sliding window from biggest: when a+b <= c move next, discard the c, otherwise finish. When c is bigger than closes a+b, then it will be bigger than any other pair sum.

Approach

  • this is not an easy problem

Complexity

  • Time complexity: \(O(nlog(n))\)

  • Space complexity: \(O(n)\) or O(1)

Code


// 81ms
    fun largestPerimeter(n: IntArray) =
        max(0, n.sorted().windowed(3)
        .maxOf{(a,b,c) -> (a+b+c)*(a+b).compareTo(c)})


// 0ms
    pub fn largest_perimeter(n: Vec<i32>) -> i32 {
        n.iter().sorted_by_key(|&x|-x).tuple_windows()
        .find(|&(c,b,a)| a+b>*c).map_or(0, |(a,b,c)| a+b+c)
    }