Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Solution {
- public int[] solve(int[] A, int B) {
- int[] result = new int[A.length];
- int start = 0, end = 0; // start inclusive, end exclusive
- Map<Integer, Integer> map = new HashMap<>();
- for (start = 0; start < A.length; start++) {
- // find the good-subarray of maximum size starting from start
- while (end < A.length && (map.size() < B || map.containsKey(A[end]))) {
- // add end to the map
- map.compute(A[end++], (__, val) -> (val == null) ? 1 : val + 1);
- }
- // increase the count of good-subarrays of size (end - start)
- result[end - start - 1]++;
- // remove start from the map
- map.compute(A[start], (__, val) -> (val == 1) ? null : val - 1);
- }
- // a good-subarray of size k also contains a good-subarray of
- // any size smaller than k starting from the same position
- for (int i = A.length - 2; i >= 0; i--) {
- result[i] += result[i + 1];
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement