Maximum Perimeter Triangle

Sort by

recency

|

109 Discussions

|

  • + 0 comments

    Rust best solution

    If you’re looking for solutions to the 3-month preparation kit in either Python or Rust, you can find them below: my solutions

    fn maximum_perimeter_triangle(sticks: &[i32]) -> Vec<i32> {
        //Time complexity: O(n*log(n))
        //Space complexity (ignoring input): O(n)
        let mut sorted_sticks = sticks.to_vec();
        sorted_sticks.sort_unstable_by(|a, b| b.cmp(a));
        for index in 0..(sorted_sticks.len() - 2) {
            if sorted_sticks[index] < sorted_sticks[index + 1] + sorted_sticks[index + 2] {
                let mut triangle = vec![
                    sorted_sticks[index],
                    sorted_sticks[index + 1],
                    sorted_sticks[index + 2],
                ];
                triangle.sort_unstable();
    
                return triangle;
            }
        }
    
        vec![-1]
    }
    
  • + 0 comments

    Python best solution

    If you’re looking for solutions to the 3-month preparation kit in either Python or Rust, you can find them below: my solutions

        #Time complexity: O(n*log(n))
        #Space complexity (ignoring input): O(1)
        sticks.sort(reverse=True)
        for index in range(0, len(sticks) - 2):
            if sticks[index] < sticks[index + 1] + sticks[index + 2]:
                triangle = [sticks[index], sticks[index + 1], sticks[index + 2]]
                triangle.sort()
                return triangle
    
        return [-1]
    
  • + 1 comment

    Can anyone explain why is there a need to sort the sticks array first?

  • + 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,)