Niu Ke Niu Niu's sequence

Portal

Title description

Niuniu now has a sequence of n numbers. Niuniu now wants to take a continuous subsequence, and this subsequence must also be satisfied: only one number can be changed at most to make this continuous subsequence a strictly ascending subsequence. Sequence, Niuniu wants to know the longest length of this continuous subsequence.

Enter description:

The input consists of two lines. The first line includes an integer n (1 ≤ n ≤ 10^5), which is the length of the sequence; the
second line has n integers a_i, representing each number in the sequence (1 ≤ a_i ≤ 10^9 ), separated by spaces.

Output description:

Output an integer, indicating the longest length.
Example 1

enter

6
7 2 3 1 5 6

Output

5

Code

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+100;
int l[N],r[N],a[N];//正向连续递增,反向连续递减 
int main()
{
    
    
	int n;
	cin>>n;
	for(int i=1;i<=n;i++) cin>>a[i];
	for(int i=1;i<=n;i++){
    
    
		//初始都为1 
		l[i]=1;
		r[i]=1;
	}
	//递推求两种数列 
	for(int i=2;i<=n;i++){
    
    
		if(a[i]>a[i-1]){
    
    
			l[i]=l[i-1]+1;
		}
	}
	for(int i=n-1;i>=1;i--){
    
    
		if(a[i]<a[i+1]){
    
    
			r[i]=r[i+1]+1;
		}
	}
	int ans=0;
	for(int i=1;i<=n;i++){
    
    
		ans=max(ans,l[i]);//可能不需要修改就是最长的了 
		if(a[i+1]-a[i-1]>=2){
    
    //可修改的情况,需要判断前后是否能连在一起 
			ans=max(ans,l[i-1]+r[i+1]+1);
		}
	}
	cout<<ans<<endl;
	/*for(int i=1;i<=n;i++) cout<<l[i]<<" ";
	cout<<endl;
	for(int i=1;i<=n;i++) cout<<r[i]<<" ";*/
	return 0;
}
/*
6 
7 2 3 1 5 6
*/ 

to sum up

Mainly still thinking mode, as long as you think of the method problem, it is easy to solve

Guess you like

Origin blog.csdn.net/Lzhzl211/article/details/114785823