I've created a function about which I though that it is a dynamic programming approach but I've found out that DP
can be Bottom-Up but this function is Top-Down. Now, I'm trying to convert this function to Bottom-Up
. Do you guys have any hints?
There are 3*n
apples (3,6,9.. or 81..) and 3 buyers. Each buyer is able to buy each apple for different price. The input is a list (apples) of prices. [[1,2],[4,5]]
means that the first apple can be sold for 1$ to first buyer and for 2$ to second buyer.
The function returns the best price you can earn.
The only thing I want is to convert it from Top-Down
to Bottom-up
so I can use dynamic programming but I have no success.
apples = [[1,50,1], [1,50,1], [1,80,50]] (3 apples for example)
results = {}
def sell_apples(buyer1, buyer2, buyer3):
global results
if (buyer1,buyer2,buyer3) in results.keys(): # memoization
return results[(buyer1,buyer2,buyer3)]
n = sum([buyer1, buyer2, buyer3])
if buyer1 == buyer2 == buyer3 == 0 or n == 0:
return 0
os = []
for i in range(3):
buyers = [buyer1, buyer2, buyer3]
if buyers[i] > 0:
buyers[i] -= 1
os.append(sell_apples(*buyers) + apples[n - 1][i])
m = max(os)
results[(buyer1,buyer2,buyer3)]=m # memoization
return m
DP Bottom-Up approach: (this is as far as I get)
def sell_apples_bottom_up(buyer1,buyer2,buyer3):
n = sum([buyer1, buyer2, buyer3])
def sabu(buyer1,buyer2,buyer3):
if all(x==0 for x in [buyer1,buyer2,buyer3]):
return 0
os = []
for i in range(3):
buyers = [buyer1,buyer2,buyer3]
if buyers[i]>0:
buyers[i] -= 1
os.append(sabu(*buyers))
m = max(os)
return m
# LOST HERE