# Sliding window and calculate counts

#### Sliding Windows prerequisite: all elements in Array shall >=0

* The count we added to ret shall be **count** of the possible startIndex&#x20;

We can use atmost helper function

```java
  public int subarraysWithKDistinct(int[] A, int K) {
        return atMost(A, K) - atMost(A, K-1);
    }
    
    
    public int atMost(int[] A, int k){
        int count = 0, start = 0, end = 0;
        int[] map = new int[A.length+1];
        while(end < A.length){
            int num = A[end];
            if(map[num] == 0){
                k--;
            }
            map[num]++;
            while(k < 0 && start <= end){
                int num2 = A[start];
                map[num2]--;
                if(map[num2] == 0){
                    k++;
                }
                start++;
            }
            count += end - start + 1; 
            end++;
        }
        return count;
    }
```

**If the element in Arrays could be negative, we shall solve it as HashMap as Two sum problem**

&#x20;
