题解 | #乘积为正数的最长连续子数组#

从头学动态规划,还不熟练,这个题想了很久|_|,希望以后能更加熟练

思路:

  1. 用一个变量Temp存储负数的数量,初始化为0;

  2. 设置两个DP数组:dpNeg和dpPos,初始化为0;

  3. 从头遍历输入的数组aInList,dpNeg[i]每次减一。

    判断aInList[i],

     若为负,Temp加一,
     若为0就重置Temp,dpNeg和dpPos为0;
    

    判断Temp:

     若为偶数,dpPos[i] 赋值为dpNeg[i]的绝对值,
     若为奇数,dpPos[i] 赋值为dpNeg[i]
    

以下为代码

while True:
    try:
        aIn = int(input())
        aInList = list(map(int,input().split()))
        #print(aInList)
        dpPos = [0]*aIn
        dpNeg= [0]*aIn
        temp = 0
        for i in range(aIn):
            dpNeg[i] = dpNeg[i-1]-1
            if aInList[i]==0:
                temp = 0
                dpPos[i] = 0
                dpNeg[i] = 0
            elif aInList[i]<0:
                temp += 1
            if temp%2==0:
                dpPos[i] = dpNeg[i]*-1
            else:
                dpPos[i] = dpNeg[i]


        print(max(dpPos))
    except:
        break

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务