[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.

[Algorithm] Flowerbox: Dynamic programming

2. Draw the DAG:

[Algorithm] Flowerbox: Dynamic programming

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

 

上一篇:EF 动态构造排序 Func, IOrderedQueryable> Dynamic


下一篇:C++基础语法---四种cast操作符