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