Implement it as user2566092:
def f(n): return max(fl(n),fh(n)) def fl(n): if n>=0: return f(n-1)+x["low"][n] else: return 0 def fh(n): if n>=0: return f(n-2)+x["high"][n] else: return 0 x={"low":(30,5,20,25,500),"high":(0,50,70,100,110)} print f(4)
EDIT: if you want it in O (n):
x={"low":(30,5,20,25,500),"high":(0,50,70,100,110)} flist=[] fhlist=[] fllist=[] for i in range(5): if i-1>0: fllist.append(flist[i-1]+x["low"][i]) else: fllist.append(x["low"][i]) if i-2>=0: fhlist.append(flist[i-2]+x["high"][i]) else: fhlist.append(x["high"][i]) flist.append(max(fhlist[i],fllist[i])) print fllist print fhlist print flist #[30, 5, 70, 125, 650] #[0, 50, 100, 150, 210] #[30, 50, 100, 150, 650]
source share