笔试编程题汇总(5)

"""
对于输入A,如果A[i-1]>A[i]

"""
基本思想:
    遍历数组A,而且只遍历一遍,记录最大的山谷长度,时间复杂度是O(n)
"""



import sys

def findValleyLen(A):
    valley_left = []
    valley_right = []
    len_max = 0
    
    for idx in range(len(A)):
        if len(valley_left)==0:
            valley_left.append(A[idx])
        else:
            if len(valley_right)==0:#left
                if A[idx]<valley_left[-1]:
                    valley_left.append(A[idx])
                elif A[idx]>valley_left[-1]:
                    if len(valley_left)>=2:
                        valley_right.append(A[idx])
                    else:
                        valley_left=[]
                        valley_left.append(A[idx])
                else:#equal
                    valley_left=[]
                    valley_left.append(A[idx])
            else:#right
                if A[idx]>valley_right[-1]:
                    valley_right.append(A[idx])
                elif A[idx]<=valley_right[-1]:
                    len_this = len(valley_left)+len(valley_right)
                    if len_this>len_max:
                        len_max=len_this
                        #valley = valley_left+valley_right
                    valley_left=[]
                    valley_left.append(valley_right[-1])
                    valley_left.append(A[idx])
                    valley_right=[]
                else:#equal
                    pass

    #the last one
    if len(valley_right)>0:
        len_this = len(valley_left)+len(valley_right)
        if len_this>len_max:
            len_max=len_this
            #valley = valley_left+valley_right
    
    return len_max if len_max>=3 else 0# valley
    

if __name__=="__main__":
    line = sys.stdin.readline().strip()
    if len(line)<3:
        print(0)
    else:
        line = line[1:-1]
        value = map(int, line.split(','))
        A = list(value)
        print(findValleyLen(A))

你可能感兴趣的:(Python,算法)