For each number in the array , we need to know its first occurrence in the array and the last occurence in the array . We will store the first occurrence of every element in hashmap(or array) a1 and last occurrence of every element in hashmap(or array) b1 .
Example :
5 6 5 2 2 6 7 7
Position of first occurrence of 5 : 1
Position of last occurrence of 5 : 3
Possible length = (3-1) = 2 .
Similarly, we do for numbers : 6,2,7 and find the maximum of all possible lengths .
Code :
#include <bits/stdc++.h>
using namespace std;
int a1[1000000+10];
int b1[1000000+9];
int main()
{
int n ;
cin>>n ;
int a[n] ;
int i = 0 ;
while(i<n)
{
cin>>a[i];
b1[a[i]]=i ;
i++;
}
i = n - 1 ;
while(i>=0)
{
a1[a[i]]=i ;
i--;
}
int maxi = -1 ;
i=1;
while(i<=1000000)
{
int possible = abs(a1[i]-b1[i]) + 1 ;
maxi = max(maxi,possible);
i++;
}
cout<<maxi ;
return 0;
}