Java sliding window with indices queue
Maintain sliding window within i and j. (j not included)\nindices maintains all the indices for each value in the sliding window.\nminEnd is the minimum end ind
Maintain sliding window within `i` and `j`. (`j` not included)\n`indices` maintains all the indices for each value in the sliding window.\n`minEnd` is the minimum end index of possible valid subarrays within current sliding window.\nUpdate `minEnd` while `i` or `j` is moving. For example:\n```\n[1, 2, 1, 2, 3]    K = 2\n i           j\nindices: {\n\t1: [0, 2]\n\t2: [1, 3]\n}\nminEnd: 1\nresult += j - minEnd = 3\n\n------\n\n[1, 2, 1, 2, 3]    K = 2\n    i        j\nindices: {\n\t1: [2]\n\t2: [1, 3]\n}\nminEnd: 2\nresult += j - minEnd = 3 + 2 = 5\n\n------\n\n[1, 2, 1, 2, 3]    K = 2\n       i     j\nindices: {\n\t1: [2]\n\t2: [3]\n}\nminEnd: 3\nresult += j - minEnd = 5 + 1 = 6\n\n......\n```\n```\nclass Solution {\n    public int subarraysWithKDistinct(int[] A, int K) {\n        int result = 0, n = A.length, i = 0, j = 0, minEnd = -1;\n        Map<Integer, Queue<Integer>> indices = new HashMap<>();\n        while (j < n) {\n            while (j < n) {\n                if (!indices.containsKey(A[j])) {\n                    if (indices.size() == K - 1) {\n                        minEnd = j;\n                    }\n                    if (indices.size() == K) {\n                        break;\n                    }\n                    indices.put(A[j], new LinkedList<>());\n                }\n                indices.get(A[j]).offer(j);\n                j++;\n            }\n            if (j == n && indices.size() < K) {\n                break;\n            }\n            while (i < j) {\n                int cur = A[i++];\n                result += j - minEnd;\n                indices.get(cur).poll();\n                if (indices.get(cur).isEmpty()) {\n                    indices.remove(cur);\n                    break;\n                }\n                minEnd = Math.max(minEnd, indices.get(cur).peek());\n            }\n        }\n        return result;\n    }\n}\n```
['Queue', 'Sliding Window', 'Java']