Advertisement
dorucriv

Good Subarrays

Apr 2nd, 2020
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1. public class Solution {
  2.     public int[] solve(int[] A, int B) {
  3.         int[] result = new int[A.length];
  4.         int start = 0, end = 0; // start inclusive, end exclusive
  5.         Map<Integer, Integer> map = new HashMap<>();
  6.        
  7.         for (start = 0; start < A.length; start++) {
  8.             // find the good-subarray of maximum size starting from start
  9.             while (end < A.length && (map.size() < B || map.containsKey(A[end]))) {
  10.                 // add end to the map
  11.                 map.compute(A[end++], (__, val) -> (val == null) ? 1 : val + 1);
  12.             }
  13.            
  14.             // increase the count of good-subarrays of size (end - start)
  15.             result[end - start - 1]++;
  16.            
  17.             // remove start from the map
  18.             map.compute(A[start], (__, val) -> (val == 1) ? null : val - 1);
  19.         }
  20.        
  21.         // a good-subarray of size k also contains a good-subarray of
  22.         // any size smaller than k starting from the same position
  23.         for (int i = A.length - 2; i >= 0; i--) {
  24.             result[i] += result[i + 1];
  25.         }
  26.        
  27.         return result;
  28.     }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement