3 ms·
This is a fairly standard dynamic programming problem. The crucial insight is that if you take two pins with a single ball, you split the problem into two indep
by sltkr 2y ago
This is a fairly standard dynamic programming problem. The crucial insight is that if you take two pins with a single ball, you split the problem into two independent subproblems, so the core question is when to hit two pins at once.
This lends itself to a solution that doesn't use dictionaries or even lists. To decide whether you want to: skip the current pin, take the current pin alone, or take the current pin together with the previous, you only need to keep track of the previous pin's value, and the past two scores. For example, in Python:
values = [3, 4, -1, 6, -1, 6, 6, 3, -1, -1, 6, -2]
prev_val = prev_score = score = 0
for val in values:
prev_val, prev_score, score = val, score, max(score, score + val, prev_score + val * prev_val)
print(score) # 64
(This solution still has a list with the input values, but it is only iterated over, so you could just as easily read those one-by-one from an input file, for an O(1) memory solution.)