I'm learning Dynamic Programming, following the topcoder guide. I just solved the BadNeighbors puzzle. It passes all the test cases, but I don't have much experience, so I don't know if it's good.
Puzzle Description:
Each of the town's residents is willing to donate a certain amount, as specified in the
int[]
donations, which is listed in clockwise order around the well. However, nobody is willing to contribute to a fund to which his neighbor has also contributed. Next-door neighbors are always listed consecutively in donations, except that the first and last entries in donations are also for next-door neighbors. You must calculate and return the maximum amount of donations that can be collected.
def circle(lst):
if len(lst) == 1:
return lst[0]
attempt_1 = _circle(lst, 0, len(lst)-1)
attempt_2 = _circle(lst, 1, len(lst))
return max(attempt_1, attempt_2)
def _circle(lst, start, end):
prev, best = 0, 0
for i in xrange(start, end):
val = lst[i]
current = val + best
best = max(prev, best)
prev = current
return best
Edit: Check the comments of my selected answer for the full resolution.