Sherlock and Cost

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zjucor/article/details/82493408

https://www.hackerrank.com/challenges/sherlock-and-cost/problem

一开始想贪心,高低交错来,但是这种贪心法是有问题的,比如100 1 2 100,用这种贪心法没法取到2个大头,

正解是DP,只有2个状态,当前数取1,或者max

# Complete the cost function below.
def cost(B):
    n=len(B)
    s0=s1=0
    for i in range(1,n):
        tmp=s0
        s0=max(s0,s1+abs(B[i-1]-1))
        s1=max(s1+abs(B[i]-B[i-1]),tmp+abs(B[i]-1))
    return max(s0,s1)

猜你喜欢

转载自blog.csdn.net/zjucor/article/details/82493408
今日推荐