Largest Perimeter Triangle in Python

Suppose we have an array A of positive lengths, we have to find the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths. When it is impossible to form any triangle of non-zero area, then return 0.

So, if the input is like [3,6,2,3], then the output will be 8.

To solve this, we will follow these steps −

  • sort the list A
  • a := delete last element from A
  • b := delete last element from A
  • c := delete last element from A
  • while b+c <= a, do
    • if not A is non-zero, then
      • return 0
    • a := b
    • b := c
    • c := delete last element from A
  • return a+b+c

Let us see the following implementation to get better understanding −


 Live Demo

class Solution:
   def largestPerimeter(self, A):
      a, b, c = A.pop(), A.pop(), A.pop()
      while b+c<=a:
         if not A:
            return 0
            a, b, c = b, c, A.pop()
   return a+b+c
ob = Solution()