Pagini recente » Cod sursa (job #321928) | Cod sursa (job #2620141) | Cod sursa (job #1278031) | Cod sursa (job #1144349) | Cod sursa (job #1510254)
#include <stdio.h>
#include <map>
#define nmax 5010
using namespace std;
int n,i,j,t[nmax],b[nmax],sol[nmax],v,nr,maxx,minn,soll;
map <int,int> mp;
inline int max(int a,int b) { if (a>b) return a; else return b; }
inline int min(int a,int b) { if (a<b) return a; else return b; }
int cauta(int st,int dr,int x)
{
int m;
while (st<=dr) {
m=(st+dr)/2;
if (sol[m]<x) st=m+1; else dr=m-1;
}
return st;
}
int main() {
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
scanf("%d",&n); minn=0x3f3f3f3f;
for (i=1;i<=n;i++) {
scanf("%d",&t[i]); mp[t[i]]++;
if (mp[t[i]]==1) nr++;
maxx=max(maxx,t[i]); minn=min(minn,t[i]);
}
if (n==1) { puts("1"); return 0; }
sol[1]=t[1]; b[1]=1; v=1;
for (i=2;i<=n;i++) {
j=cauta(1,v,t[i]); sol[j]=t[i];
b[i]=j; v=max(v,j);
}
j=v;
if (nr!=v) { puts("-1"); return 0; }
for (i=1;i<=n;i++)
if (t[i]==minn) {
for (j=n;j>=i+1;j--)
if (b[j]==nr && t[j]==maxx) {
soll=max(soll,j-i+1);
}
}
printf("%d",soll);
return 0;
}