牛客网编程题——牛牛的数列(至多调整一个得到的最长上升子区间)

在这里插入图片描述
先找到所有上升区间的起始位置索引
存为
[(start1,end1),(start2,end2),…]
然后从上面第二个区间开始 依次探讨和其前一个区间合并的可能性
假设原数组为l
合并的条件是
start2 = end1 + 1 and l[end1] > l[start2] and l[end1] < l[start2+1]

start2 = end1 + 1 and l[end1] > l[start2] and l[end1-1] < l[start2]
当满足上述条件之一时
我们计算当前长度最大值和end2-start1+1的大小 取更大的那个

n = int(input())
l = [int(val) for val in input().split(' ')]
if n == 1:
    print(1)
else:
    res_list = []
    start = -1
    index = 1
    maxlen = 1
    while index < n:
        if l[index] > l[index - 1]:
            if res_list == [] or len(res_list[-1]) == 2:
                res_list.append([index-1])
        elif l[index] <= l[index - 1]:
            if res_list != [] and len(res_list[-1]) == 1:
                res_list[-1].append(index-1)
        index += 1
    if len(res_list[-1]) == 1:
        res_list[-1].append(n-1)
    if len(res_list) == 1:
        print(res_list[0][1]-res_list[0][0]+1)
    else:
        templen = len(res_list)
        maxlen = res_list[0][1] - res_list[0][0] + 1
        for i in range(1,templen):
            if res_list[i-1][1] + 1 == res_list[i][0] and l[res_list[i-1][1]] > l[res_list[i][0]] and l[res_list[i-1][1]] < l[res_list[i][0]+1]:
                maxlen = max(maxlen,res_list[i][1]-res_list[i-1][0]+1)
            elif res_list[i-1][1] + 1 == res_list[i][0] and l[res_list[i-1][1]] > l[res_list[i][0]]  and l[res_list[i-1][1]-1] < l[res_list[i][0]]: 
                maxlen = max(maxlen,res_list[i][1]-res_list[i-1][0]+1)
        print(maxlen)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值