Largest Perimeter Triangle in O(NLogN)

Problem is this: https://leetcode.com/problems/largest-perimeter-triangle/description/

Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths.
If it is impossible to form any triangle of non-zero area, return 0.

    Example 1:
    Input: [2,1,2]
    Output: 5
    
    Example 2:
    Input: [1,2,1]
    Output: 0
    
    Example 3:
    Input: [3,2,3,4]
    Output: 10
    
    Example 4:
    Input: [3,6,2,3]
    Output: 8
    

    Note:
    1. 3 <= A.length <= 10000
    2. 1 <= A[i] <= 10^6

    Remember that for a triangle to be valid with Area > 0, the following condition must be true:

    Side1 + Side2 > Side3

    Notice that you can't use greater than or equal since the equal means area = 0. The solution becomes straightforward if you sort the array: from largest to smallest, find the first triplet matching the aforementioned condition, and then you're done. Hence O(NLogN) in 4 lines of code. Thanks! A.C.C.


    public class Solution
    {
     public int LargestPerimeter(int[] A)
     {
      if (A == null || A.Length < 3) return 0;
      Array.Sort(A);
      for (int i = A.Length - 3; i >= 0; i--) if (A[i] + A[i + 1] > A[i + 2]) return A[i] + A[i + 1] + A[i + 2];
      return 0;
     }
    }
    

    Comments

    1. Cannot get any more elegant :) My C++ solution is almost identical:

      class Solution {
      public:
      int largestPerimeter(vector& A) {
      sort(A.begin(), A.end());
      for (int i = A.size()-1; i >= 2; --i) {
      if (A[i] < A[i-1] + A[i-2]) return A[i] + A[i-1] + A[i-2];
      }
      return 0;
      }
      };

      ReplyDelete

    Post a Comment

    Popular posts from this blog

    Advent of Code - Day 6, 2024: BFS and FSM

    Golang vs. C#: performance characteristics (simple case study)

    Advent of Code - Day 7, 2024: Backtracking and Eval