For this type of questions, i.e. minimal cost to equalize a list of numbers, the key is to note that

**the minmum cost is always achieved when the equal length = one number from the list**

e.g. if sticks' heights are [1,4,7], the equal length with minimum cost must be one from 1,4,7, rather than those from 0,5,6,8. etc. Try to prove it by contradiction.

With this obseration, sort stick heights, for every possible height, calculate the total cost to equalize all sticks in O(n), and then pick the smallest cost.

def magic(n,sticks,cost):

#costs=[0]*n #cost[i] is the cost to make all sticks equal to stick[i] length

```
prices=set()
for i in range(len(sticks)):
req=sticks[i]
tot=0
for j in range(len(sticks[:i])):
k=sticks[j]
while(k<req):
k+=1
tot+=cost[j]
while(k>req):
k-=1
tot+=cost[j]
for j in range(i+1,len(sticks)):
k=sticks[j]
while(k<req):
k+=1
tot+=cost[j]
while(k>req):
k-=1
tot+=cost[j]
prices.add(tot)
return min(prices)
```

print(magic(2,[1,2],[10,20]))

print(magic(3,[1,2,3],[20,30,40]))