fork download
  1. // TC : O(N^2)
  2. // SC : O(N)
  3.  
  4. #include <iostream>
  5. #include<unordered_map>
  6. using namespace std;
  7.  
  8. int main() {
  9. int n;
  10. cin >> n;
  11.  
  12. int arr[n];
  13. for(int i=0; i<n; i++) {
  14. cin >> arr[i];
  15. }
  16.  
  17. int count = 0;
  18. int k;
  19. cin >> k;
  20.  
  21. int sum = 0;
  22. unordered_map<int, int> mp;
  23.  
  24. for(int i=0, j=0; j < n; j++) {
  25. mp[arr[j]]++; // [i ............... j]
  26.  
  27. int distinct = mp.size();
  28.  
  29. while(distinct > k) {
  30. mp[arr[i]]--;
  31. if(mp[arr[i]] == 0) {
  32. mp.erase(arr[i]);
  33. }
  34. i++;
  35.  
  36. distinct = mp.size();
  37. }
  38. count += (j - i + 1);
  39. }
  40. cout << "Count : " << count;
  41. return 0;
  42. }
Success #stdin #stdout 0s 5320KB
stdin
5
1
2
2
5
8
4
stdout
Count : 15