Advertisement
nikunjsoni

992

Apr 10th, 2021
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.56 KB | None | 0 0
  1. class Solution {
  2. public:
  3.    
  4.     int atMostK(vector<int>& A, int K){
  5.         int ans = 0, n=A.size(), right, left;
  6.         unordered_map<int, int> count;
  7.        
  8.         for(left=right=0; right<n; right++){
  9.             if(!count[A[right]]++) K--;
  10.             while(K < 0){
  11.                 if(--count[A[left]] == 0) K++;
  12.                 left++;
  13.             }
  14.             ans += (right-left+1);
  15.         }
  16.         return ans;
  17.     }
  18.    
  19.     int subarraysWithKDistinct(vector<int>& A, int K) {
  20.         return atMostK(A, K) - atMostK(A, K-1);
  21.     }
  22. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement