[Algorithm] Flowerbox: Dynamic programming

A serial of number, you cannot add siblings number together. To calcaulate what is the max sum value.

Thinking:

1. Weather I should add current number or not.

2. Draw the DAG:

From the DAG, can see that F(n), only need F(n-2) and F(n-1) two variables.

Code:

def flower_box(n):
    a = 0
    b = 0

    for i in n:
        a,b = b, max(a + i, b)

    return b


flower_box([3,10,3,1,2]) // 12
flower_box([9,10,9])//18
原文地址:https://www.cnblogs.com/Answer1215/p/14294226.html