Maximum Perimeter Triangle

  • + 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]
    }