首页 > 试题广场 >

最长和谐连续子序列

[编程题]最长和谐连续子序列
  • 热度指数:1744 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
和谐连续序列是指一个连续序列中元素的最大值和最小值之间的差值正好是1。
现在,给定一个整数数组,你需要在所有可能的连续子序列中找到最长的和谐连续子序列的长度。

输入描述:
一行整数数组,由空格分割


输出描述:
一行一个数字表示答案,即最长和谐连续子序列的长度
示例1

输入

1 3 2 2 5 2 3 7

输出

3

说明

最长的连续和谐子序列是:[3,2,2]
示例2

输入

1 3 2 2 1 1 2 3

输出

5

说明

最长的连续和谐子序列是:[2,2,1,1,2]
if len(A)==1:  #处理特例
    print(0)
else:          #非特例
    i=0
    j=0
    maxc=0
    while i<len(A):
        j=i
        t=[]
        tmin=A[j]
        tmax=A[j]
        while(tmax-tmin<=1 and j<len(A)  and abs(A[j]-tmin)<=1 and abs(A[j]-tmax)<=1):
            t.append(A[j])
            tmin=min(t)
            tmax=max(t)
            j=j+1
        c=len(t)
        if len(set(t))==1:
            c=0
        if c>maxc:
            maxc=c
        i=i+1
    print(maxc)

发表于 2021-05-18 19:16:03 回复(1)
from collections import deque
nums = list(map(int,input().split(' ')))
temp= deque()
len_max=0
def max_dis(temp):
    n_min=n_max=temp[0]
    for i in range(1,len(temp)):
        if temp[i]>n_max:n_max=temp[i]
        if temp[i]<n_min:n_min=temp[i]
    return n_max-n_min

for i in nums:
    temp.append(i)
    while temp and max_dis(temp)>1:
        temp.popleft()
    if temp and max_dis(temp)==1:
        if len(temp)>len_max:
            len_max=len(temp)
print(len_max)
发表于 2021-03-30 10:26:19 回复(0)