Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
Triangle Inequality Rule
For three sides to form a triangle, they must satisfy the triangle inequality: the sum of any two sides must be greater than the third side. For sides a, b, c where a ? b ? c, we only need to check if b + c > a.
Algorithm Steps
To solve this, we will follow these steps:
Sort the array in descending order
Take the three largest values (a, b, c)
Check if they form a valid triangle using b + c > a
If not valid, move to the next set of three values
Return the perimeter of the first valid triangle found, or 0 if none exists
Example
def solve(nums):
nums.sort()
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]
print(solve(nums))
19
How It Works
Let's trace through the example [8, 3, 6, 4, 2, 5]:
nums = [8, 3, 6, 4, 2, 5]
print("Original array:", nums)
nums.sort()
print("Sorted array:", nums)
# After sorting: [2, 3, 4, 5, 6, 8]
# Pop three largest: a=8, b=6, c=5
# Check: b + c = 6 + 5 = 11 > 8 ?
# Valid triangle with perimeter = 8 + 6 + 5 = 19
def solve_with_trace(nums):
nums.sort()
print(f"Sorted: {nums}")
a, b, c = nums.pop(), nums.pop(), nums.pop()
print(f"Testing sides: a={a}, b={b}, c={c}")
while b + c <= a:
print(f"Invalid: {b} + {c} = {b+c} <= {a}")
if not nums:
print("No more combinations available")
return 0
a, b, c = b, c, nums.pop()
print(f"Next combination: a={a}, b={b}, c={c}")
print(f"Valid triangle: {a} + {b} + {c} = {a+b+c}")
return a + b + c
result = solve_with_trace([8, 3, 6, 4, 2, 5])
Original array: [8, 3, 6, 4, 2, 5] Sorted array: [2, 3, 4, 5, 6, 8] Sorted: [2, 3, 4] Testing sides: a=4, b=3, c=2 Valid triangle: 4 + 3 + 2 = 9
Edge Cases
# Case 1: No valid triangle possible
print("Case 1:", solve([1, 1, 10])) # 1 + 1 = 2 <= 10
# Case 2: All equal sides
print("Case 2:", solve([3, 3, 3])) # Valid equilateral triangle
# Case 3: Minimum array size
print("Case 3:", solve([1, 2, 3])) # 1 + 2 = 3 <= 3 (not valid)
print("Case 4:", solve([2, 3, 4])) # 2 + 3 = 5 > 4 (valid)
Case 1: 0 Case 2: 9 Case 3: 0 Case 4: 9
Conclusion
This algorithm efficiently finds the largest perimeter triangle by sorting the array and checking combinations from largest to smallest. The triangle inequality ensures we find a valid triangle, and the greedy approach guarantees the maximum perimeter.
