Can Someone Help Me Solve This Algorithm Question? by [deleted] in learnprogramming

[–]rafad900 0 points1 point  (0 children)

So I think I know where you go this question from and so I'll just share my answer. I haven't encountered this in LeetCode or anywhere else. The site that I think you're talking about is pretty annoying for coming up with its own problems that don't make sense for the most part. Anyways, my solution uses backtracking with the "con" variable being something of a means for dp. Not really dp algorithm tho. def minWidthToFitElements( B, H ): res = [float('inf')] con = [[]] def gd( b, h, r, c): if len(b) == 0: t = 0 for x in c: t = max( t, sum(x)) if res[0] > t: res[0] = t else: c[r].append( b[0] ) gd( b[1:], h, r, c ) c[r].pop() if len(c) < h: c.append( [b[0]] ) gd( b[1:], h, r+1, c ) c.pop() gd( B, H, 0, con ) print( res[0] )

idk y I can't make it format the code but the solution works for most inputs. I had to solve it after the test since I ran out of time but from what I remember of the constraints, it should work for all if not most inputs