We are all familiar with sorting algorithms: quick sort, merge sort, heap sort, insertion sort, selection sort, bubble sort, etc. But sometimes it is an overkill to use these algorithms for an almost sorted array.
We say an array is sorted if its elements are in non-decreasing order or non-increasing order. We say an array is almost sorted if we can remove exactly one element from it, and the remaining array is sorted. Now you are given an array a1,a2,…,an a1,a2,…,an, is it almost sorted?
We say an array is sorted if its elements are in non-decreasing order or non-increasing order. We say an array is almost sorted if we can remove exactly one element from it, and the remaining array is sorted. Now you are given an array a1,a2,…,an a1,a2,…,an, is it almost sorted?
1≤T≤2000 1≤T≤2000
2≤n≤105 2≤n≤105
1≤ai≤105 1≤ai≤105
There are at most 20 test cases with n>1000 n>1000.
3 3 2 1 7 3 3 2 1 5 3 1 4 1 5
YES YES NO
#include<stdio.h>
#include<string.h>
int stack[100000];
int top;
int f(int x)
{
int l=0,r=top;
int mid;
while(r>=l)
{
mid=(l+r)/2;
if(x>=stack[mid])
l=mid+1;
else
r=mid-1;
}
return l;
}
int main()
{
int t,n,m,j,i,k;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
int s[100000];
for(i=1;i<=n;i++)
scanf("%d",&s[i]);
top=0;
stack[0]=-1;
for(i=1;i<=n;i++)
{
if(s[i]>=stack[top])
stack[++top]=s[i];
else
stack[f(s[i])]=s[i];
}
int ans=top;
memset(stack,0,sizeof(0));
top=0;
stack[0]=-1;
for(i=n;i>=1;i--)
{
if(s[i]>=stack[top])
stack[++top]=s[i];
else
stack[f(s[i])]=s[i];
}
int ant=top;
if(n-ant<=1||n-ans<=1)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}