Remove One Element(贪心)

You are given an array aa consisting of nn integers.

You can remove at most one element from this array. Thus, the final length of the array is n−1n−1 or nn.

Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.

Recall that the contiguous subarray aa with indices from ll to rr is a[l…r]=al,al+1,…,ara[l…r]=al,al+1,…,ar. The subarray a[l…r]a[l…r] is called strictly increasing if al<al+1<⋯<aral<al+1<⋯<ar.

Input
The first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of elements in aa.

The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the ii-th element of aa.

Output
Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array aa after removing at most one element.

Examples
Input
5
1 2 5 3 4
Output
4
Input
2
1 2
Output
2
Input
7
6 5 4 3 2 4 3
Output
2
Note
In the first example, you can delete a3=5a3=5. Then the resulting array will be equal to [1,2,3,4][1,2,3,4] and the length of its largest increasing subarray will be equal to 44.
思路:最多删除一个,那么我们就记录这一个数字前一个数字和后一个数字的最长连续序列。然后贪心的取最大值。事先用dfs预处理好每一个数字最远可以到达哪里。具体看代码。
代码如下:

#include<bits/stdc++.h>
#define ll long long
using namespace std;

const int maxx=2e5+100;
int a[maxx];
int dp[maxx];
int np[maxx];
int n;

inline void dfs(int &i,int &cnt)
{
	if(i==n) 
	{
		dp[n]=1;
		i+=1;
		return ;
	}
	int ant=cnt,j=i;
	if(a[i+1]>a[i]) dfs(i+=1,cnt+=1);
	else i+=1;
	dp[j]=cnt-ant+1;
}
inline void dfs1(int &i,int &cnt)
{
	if(i==1)
	{
		np[i]=1;
		i-=1;
		return ;
	}
	int ant=cnt,j=i;
	if(a[i-1]<a[i]) dfs1(i-=1,cnt+=1);
	else i-=1;
	np[j]=cnt-ant+1;
}
int main()
{
	scanf("%d",&n);
	int _max=0;
	a[n+1]=a[0]=0;
	for(int i=1;i<=n;i++) 
	{
		scanf("%d",&a[i]);
	}
	int cnt;
	for(int i=1;i<=n;) dfs(i,cnt=0);//dp[i]代表的是第i位开始,最长的上升序列,i++
	for(int i=n;i>=1;) dfs1(i,cnt=0);//np[i]代表的是第i位开始,最长的下降序列,i--
	for(int i=1;i<=n;i++) _max=max(_max,dp[i]);
	for(int i=2;i<n;i++) if(a[i-1]<a[i+1]) _max=max(_max,np[i-1]+dp[i+1]);//贪心的取最大值
	cout<<_max<<endl;
	return 0;
}//1 2 3 4 5 6 

努力加油a啊,(o)/~

发布了414 篇原创文章 · 获赞 23 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/starlet_kiss/article/details/104194160