date posted: 2020-05-05
This problem is solved using greedy approach which basically means at each step you find most optimal solution and in the end that will be global optimal solution. But we know that obtaining global optimal solution is not always true.
So this is my approach:
def check_valid_tri(triangle): """if sum of two sides > another side then it is valid triangle""" a = triangle[0] b = triangle[1] c = triangle[2] if (a + b > c) & (a + c > b) & (b + c > a): return True else: return False def maximumPerimeterTriangle(sticks): sticks.sort() triangles = [] for i, st in enumerate(sticks): triangle = sticks[i:3+i] if len(triangle) < 3: continue if check_valid_tri(triangle): triangles.append(triangle) if len(triangles) == 0: return [-1] elif len(triangles) == 1: return triangles[0] else: return triangles[-1]
This problem was pretty easy to solve, I just needed to search for ways to check whether a triangle was valid (I'm a math major).
This works perfectly, going over every three sticks (do not need to try all combinations since it is ordered and if it doens't creates valid triangle at last three it means there won't be any sticks that can be replaced to create valid triangle since a + b < c will become a + b << c)
Every three sticks can be seen as feasible solution, and we update our triangles with more feasible ones finally picking the latest feasible one which would be our most optimal solution. This is very simple greedy approach and I believe my code has done a pretty good job! :)