DZY has a sequence a, consisting of n integers.
We'll call a sequence ai, ai + 1, ..., aj (1 ≤ i ≤ j ≤ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment.
Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.
You only need to output the length of the subsegment you find.
The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109).
In a single line print the answer to the problem — the maximum length of the required subsegment.
6 7 2 3 1 5 6
5
You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4.
题意:在一个整数序列中找这样一个子段,每一个数严格大于上一个数。你可以至多改变序列中一个数的值,问最长子段的长度。
思路:先从前往后扫一遍,如果发现某个数不比上一个数大,把它置为上一个数+1,继续扫,如果又出现了这种情况,还原到原来的位置原来的值。再后往前扫一遍。比如sample:
7 2 3 1 5 6
到2的时候发现不比7大,置为8,序列是7 8 3 1 5 6,到3发现不比8大,第二次出现这种情况,还原7 2 3 1 5 6,从2开始扫。到1发现不比3大,置为4,直到最后长度是5。逆序扫同理。。
#include <iostream>
#include <stdio.h>
#include <cmath>
#include <algorithm>
#include <iomanip>
#include <cstdlib>
#include <string>
#include <memory.h>
#include <vector>
#include <queue>
#include <stack>
#include <ctype.h>
#define INF 1000000000
using namespace std;
int n;
int tab[100010];
int tab2[100010];
int main(){
while(cin>>n){
for(int i=1;i<=n;i++){
scanf("%d",&tab[i]);
tab2[i]=tab[i];
}
int ans=1;
int len=1;
int flag=false;
int k=0;
int tmp=0;
for(int i=2;i<=n;i++){
if(tab[i]>tab[i-1]){
len++;
}else{
if(!flag){
k=i;
tmp=tab[i];
tab[i]=tab[i-1]+1;
flag=true;
len++;
}else{
flag=false;
i=k;
tab[k]=tmp;
len=1;
}
}
if(len>ans)ans=len;
}
len=1;
flag=false;
k=0;
tmp=0;
for(int i=n-1;i>=1;i--){
if(tab2[i]<tab2[i+1]){
len++;
}else{
if(!flag){
k=i;
tmp=tab2[i];
tab2[i]=tab2[i+1]-1;
flag=true;
len++;
}else{
flag=false;
i=k;
tab2[k]=tmp;
len=1;
}
}
if(len>ans)ans=len;
}
cout<<ans<<endl;
}
return 0;
}