Program to find largest perimeter triangle using Python

Suppose we have an array nums of positive lengths, we have to find the largest perimeter of a triangle, by taking three values from that array. When it is impossible to form any triangle of non-zero area, then return 0.

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

To solve this, we will follow these steps −

  • sort the list nums

  • a := delete last element from nums

  • b := delete last element from nums

  • c := delete last element from nums

  • while b+c <= a, do

    • if not nums is non-zero, then

      • return 0

    • a := b

    • b := c

    • c := delete last element from nums

  • return a+b+c

Let us see the following implementation to get better understanding −


 Live Demo

def solve(nums):
   a, b, c = nums.pop(), nums.pop(), nums.pop()
   while b+c<=a:
      if not nums:
         return 0
      a, b, c = b, c, nums.pop()
   return a+b+c
nums = [8,3,6,4,2,5]