Maximum unique number from number stream
A question asked in Knowlarity , Gurgaon Interview :
You have a stream of numbers. At any time , find the maximum and the unique number at any time.
I/P: 5 6 7 7 6
O/p:5 6 7 6 5
Avaialble at https://www.geeksforgeeks.org/knowlarity-interview-experience/
Solution is as follows in C++11 :
#include<bits/stdc++.h>
#include <unordered_map>
using namespace std;
void findMaxArray(int arr[],int n)
{
int max = arr[0];
if(n==0)
{
cout << -1;
return;
}
unordered_map< int ,int> s;
s.insert(std::make_pair(arr[0],0));
int maxV[n] ;
maxV[0]=arr[0];
cout << maxV[0] << “\t”;
for (int i=1; i<n; i++)
{
if (s.find(arr[i]) == s.end())
{
if(arr[i] > maxV[i-1])
maxV[i]=arr[i];
s.insert(std::make_pair(arr[i],i));
cout << maxV[i] << “\t” ;
}
else
{
int index = s[arr[i]];
maxV[index]=-1;
int j=i-1;
for(; j >=0 ; j–)
{
if(maxV[j] != arr[i])
{
if(maxV[j] != -1)
{
maxV[i]=maxV[j];
cout << maxV[j] << “\t”;
break;
}
}
else
maxV[j]=-1;
}
if(j == -1)
{
maxV[i] = -1;
cout << -1 << “\t”;
}
}
}
}
int main()
{
int arr[] = {5,6,7,7,6};
int n = sizeof(arr)/sizeof(int);
findMaxArray(arr, n);
return 0;
}
Resolving technical problems:
Solve your technical problems instantly
We provide Remote Technical Support from Monday to Sunday, 7:00PM to 1:00 AM
Mail your problem details at [email protected] along with your mobile numberand we will give you a call for further details. We usually attend your problems within 60 minutes and solve it in maximum 2 days.