Maximum Perimeter Triangle

Sort by

recency

|

105 Discussions

|

  • + 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))
    
  • + 0 comments

    def valid_triangle(tri):

    if tri[0] + tri[1] > tri[2] and tri[1] + tri[2] > tri[0] and tri[2] + tri[0] > tri[1]:
        return True
    return False
    

    def maximumPerimeterTriangle(sticks):

    n_tri = []
    sticks.sort()
    for i in range(len(sticks)):
        tri = sticks[i:i + 3]
        if len(tri) == 3 and valid_triangle(tri):
            n_tri.append((tri, sum(tri)))
    if len(n_tri) > 0:
        m = max([i[1] for i in n_tri if i[1]])
        n = max([i[0] for i in n_tri if i[1] >= m])
    else:
        n = [-1]
    return n