Maximum Perimeter Triangle

Sort by

recency

|

106 Discussions

|

  • + 0 comments

    A non-degenerate triangle is one where the sum of the lengths of any two sides is greater than the length of the remaining side.

  • + 0 comments

    Python 3 solution:

    import typing
    
    
    def maximumPerimeterTriangle(
        sticks: list[int],
    ) -> tuple[int, int, int] | tuple[typing.Literal[-1]]:
        sticks.sort(reverse=True)
        for i in range(len(sticks) - 2):
            a, b, c = sticks[i : i + 3]
            if a < b + c:
                return c, b, a
        return (-1,)
    
  • + 0 comments

    Python 3 Solun:

    def maximumPerimeterTriangle(sticks):
        sticks.sort()
        for i in range(len(sticks) - 3, -1, -1):
            if sticks[i] + sticks[i+1] > sticks[i+2]:
                return [sticks[i], sticks[i+1], sticks[i+2]]
        return [-1]
    
  • + 0 comments

    Awesome rust solution ;)

    fn maximumPerimeterTriangle(mut sticks: Vec<i32>) -> Vec<i32> {
        sticks.sort();
        
        sticks
            .windows(3)
            .filter(|&window| window[0] + window[1] > window[2])
            .max_by_key(|&window| (window.iter().sum::<i32>(), window.iter().min().unwrap()))
            .unwrap_or(&[-1])
            .to_vec()
    }
    
  • + 0 comments

    Two pointer technique

    def maximumPerimeterTriangle(sticks):

    n = len(sticks)
    sticks.sort()
    possible_triangles = []
    for i in range(n - 1, 1, -1):
        left = 0
        right = i - 1
        while left < right:
            if sticks[left] + sticks[right] > sticks[i]:
                for k in range(left, right):
                    possible_triangles.append((sticks[k], sticks[right], sticks[i]))
                right -= 1
            else:
                left += 1
    
    if not possible_triangles:
        return [-1]
    return max(possible_triangles, key=lambda x: sum(x))