One-dimensional Dynamic Programming
126 / 170One-dimensional Dynamic ProgrammingLesson 2 of 11About 40 min
The first real choice. Two options per element, and the constraint decides what taking costs you.
Every selection of non-adjacent positions from four values is listed, with its total. Type the two lines it prints.
values = [5, 1, 1, 5] def selections(n): if n == 0: yield [] return for rest in selections(n - 1): yield rest if not rest or rest[0] > n: # positions are added descending yield [n - 1] + rest if False else rest allowed = []for mask in range(1 << len(values)): picked = [i for i in range(len(values)) if mask >> i & 1] if all(b - a > 1 for a, b in zip(picked, picked[1:])): allowed.append(picked) print(len(allowed), "legal selections")print("best total:", max(sum(values[i] for i in picked) for picked in allowed))Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.