java two pointer
To directly compute the subarray with K different nums is hard, but subarray with at most K different nums is easy.\n\nBy this idea, the rest effort is straight
To directly compute the subarray with K different nums is hard, but subarray with at most K different nums is easy.\n\nBy this idea, the rest effort is straight forward.\n\n```\nclass Solution {\n    public int subarraysWithKDistinct(int[] A, int K) {\n        return atmost(A,K)-atmost(A,K-1);\n    }\n    \n    int atmost(int[] arr, int k){\n        int count=0, i=0, j=0, ret=0;\n        HashMap<Integer, Integer> map = new HashMap<>();\n        for (;j<arr.length;){\n            if (map.getOrDefault(arr[j],0)==0) count++;\n            map.put(arr[j],map.getOrDefault(arr[j],0)+1);\n            while (count>k){\n                map.put(arr[i],map.get(arr[i])-1);\n                if (map.get(arr[i])==0) count--;\n                i++;\n            }\n            ret += j-i+1;\n            j++;\n        }\n        return ret;\n    }\n}\n```
[]