Remove One Element(dp求序列删去一个数后的最长连续的递增子序列长度 o(n))

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

Copy

5
1 2 5 3 4

output

Copy

4

input

Copy

2
1 2

output

Copy

2

input

Copy

7
6 5 4 3 2 4 3

output

Copy

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.

题意:第一行给出一个数n,接下来给出n个数的序列。求在该序列中删去任意一个数后所得序列中的最长连续的递增子序列长度。

思路:用l[i]表示从左往右遍历,以编号为i的位置为起点的从左到右的最长连续的递增子序列的长度;用r[i]表示从右往左遍历,以编号为i的位置为起点的从右到左的最长连续的递增子序列的长度,该过程可用dp的方法来记录,然后用一个变量maxlen记录当前最大长度,最后从左到右遍历一遍,if(a[i]<a[i+2])(说明去掉i+1号位置后,以i号位置为终点的最长递增序列的最后一个数a[i]小于以i+2号位置为起点的最长递增序列的第一个数a[i+2],这样这两个递增序列就可以合并成一个更大的递增序列了),所以此时maxlen更新(即:maxlen=max(maxlen,l[i]+r[i+2]))。

完整代码:

#include <bits/stdc++.h>
#define int long long
using namespace std;
const int maxn=2e5+5;
int n,a[maxn],l[maxn],r[maxn];
 
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin>>n;
    for(int i=1;i<=n;i++)//最初每个数都是一个长度为1的递增序列,所以初始化为1
        l[i]=1;
    for(int i=1;i<=n;i++)
        r[i]=1;
    for(int i=1;i<=n;i++)
        cin>>a[i];
    int maxlen=1;
    for(int i=n-1;i>=1;i--)
    {
        if(a[i]<a[i+1]){
            r[i]=r[i+1]+1;//(如:1 2 3 5 2 4,r[i]依次为4 3 2 1 2 1)
        }
        maxlen=max(maxlen,r[i]);
    }
    for(int i=2;i<=n;i++)
    {
        if(a[i]>a[i-1]){
            l[i]=l[i-1]+1;//(如:1 2 3 5 2 4,l[i]依次为1 2 3 4 1 2)
        }
        maxlen=max(maxlen,l[i]);
    }
    for(int i=1;i<=n-2;i++)
    {
        if(a[i]<a[i+2]){
            maxlen=max(maxlen,l[i]+r[i+2]);
        }
    }
    cout<<maxlen<<endl;
    return 0;
}
发布了89 篇原创文章 · 获赞 5 · 访问量 6705

猜你喜欢

转载自blog.csdn.net/Mr_Kingk/article/details/103606895