[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

 

posted @ 2021-01-18 18:21  Zhentiw  阅读(121)  评论(0编辑  收藏  举报