/// Its Work For Positive Number(Greater Than Zero)
#include<bits/stdc++.h>
#define N 1000000
using namespace std;
int position[N], preposition[N];
bool flag[N];
int main()
{
int n, value;
cout << "Enter Array Size :: ";
cin >> n;
int a[n];
cout << "\nEnter Array Element :: ";
for(int i=0;i<n;i++)
cin >> a[i];
cout << "\n";
cout << "Enter A Number :: "; /// 1 to value that subsequence search in this array
cin >> value;
for(int i=0;i<N;i++)
position[i] = -1;
for(int i=n-1;i>=0;i--)
{
preposition[i] = position[a[i]];
position[a[i]] = i;
}
int cnt = 0, left = 0, right = -1;
for(int i=0;i<N;i++)
flag[i] = false;
for(int i=0;i<n;i++)
{
if(a[i] <= value && flag[a[i]] == false)
{
flag[a[i]] = true;
cnt++;
}
if(cnt == value)
{
right = i;
break;
}
}
if(right == -1)
{
cout << "Smallest Sequence Not Found." << "\n";
return 0;
}
int minimum = right - left + 1;
while(left < right)
{
if(a[left] > value)
left++;
else if(preposition[left] == -1)
break;
else if(preposition[left] <= right)
left++;
else
{
right = preposition[left];
left++;
}
minimum = min(minimum, (right-left+1));
}
cout << "\nSmallest Subsequence Length :: " << minimum << "\n";
return 0;
}
Comments
Post a Comment