fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int getCount(vector<int>& arr){
  4. int n=arr.size();
  5. int i=0;
  6. int j=0;
  7. int maxi=0;
  8. unordered_map<int,int>mp;
  9. while(i<n && j<n){
  10. if(mp.find(arr[j])==mp.end()){
  11. mp[arr[j]]=j;
  12. int len=j-i+1;
  13. maxi=max(len,maxi);
  14. j=j+1;
  15. }
  16. else{
  17. int idx=mp[arr[j]];
  18. while(i<=idx){
  19. mp.erase(arr[i]);
  20. i++;
  21. }
  22. i=idx+1;
  23. mp[arr[j]]=j;
  24. j=j+1;
  25. }
  26. }
  27. return maxi;
  28. }
  29. int main() {
  30. // your code goes here
  31. int n;
  32. cin>>n;
  33. vector<int>arr(n);
  34. for(int i=0;i<n;i++){
  35. cin>>arr[i];
  36. }
  37. cout<<"The maximum length of distinct array elements is:"<<getCount(arr);
  38. return 0;
  39. }
Success #stdin #stdout 0.01s 5316KB
stdin
10
3 2 4 5 2 6 7 8 9 10 
stdout
The maximum length of distinct array elements is:8