leetcode最长连续上升或下降子序列

题目:给定一个整数数组,请找出最长连续上升或下降子序列 
样例:
    给定 [5, 4, 2, 1, 3], 其最长下降连续子序列为 [5, 4, 2, 1],返回 4.
    给定 [5, 1, 2, 3, 4], 其最长上升连续子序列为 [1, 2, 3, 4],返回 4.
思路:
    用动态规划解决。
    原数组记为a,设置两个数组分别存储递增以及递减连续子序列长度,记为incre和decre。
    观察一下状态转移方程,如果a[i] > a[i - 1],则incre[i] = incre[i - 1] + 1, decre[i] = 1(因为数组递增,以当前元素为结尾的,递减最长连续序列的长度当然是1)
    同理,如果a[i] < a[i - 1],那么decre[i] = decre[i - 1] + 1, incre[i] = 1def longest(a):
    if len(a)==0: return 0
    incre,decre=[1],[1]
    i,n=1,len(a)
    while i<n:
        if a[i]>a[i-1]:
            incre.append(incre[-1]+1)#不断递增
            decre.append(1)
        else:
            decre.append(decre[-1]+1)#不断递减
            incre.append(1)
        i+=1;
    print incre
    print decre
    return max(max(incre),max(decre))#选择递增递减里最大的
print longest([1,2,4,3,5,7,9,8,7,6])
'''
输出:
[1, 2, 3, 1, 2, 3, 4, 1, 1, 1]
[1, 1, 1, 2, 1, 1, 1, 2, 3, 4]
4
'''

猜你喜欢

转载自blog.csdn.net/acttell/article/details/80721110