We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
You should not use deque.contains() method, it takes long time because it traverses through all array in every loop.
I used map instead.
Scanner in = new Scanner(System.in);
Deque deque = new ArrayDeque<>();
int n = in.nextInt();
int m = in.nextInt();
int max = 0;
int curr = 0;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
int num = in.nextInt();
if (deque.size() == m) {
int last = deque.pollLast();
int val = map.get(last) - 1;
map.put(last, val);
if (val == 0) {
--curr;
}
}
if (!map.containsKey(num) || map.get(num) == 0) {
++curr;
}
deque.offerFirst(num);
max = Math.max(max, curr);
// add to map
Integer val = map.get(num);
if (val == null) val = new Integer(0);
map.put(num, val+1);
}
System.out.println(max);
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Java Dequeue
You are viewing a single comment's thread. Return to all comments →
You should not use deque.contains() method, it takes long time because it traverses through all array in every loop. I used map instead.