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.
For each deque if you pass it in a hashset to get the unique set size, it would take time if the size is huge.
Instead use a map and for each loop keep track of the occurence of deque numbers.
Here is my code take a look: ---
Scanner in = new Scanner(System.in);
ArrayDeque deque = new ArrayDeque<>();
int n = in.nextInt();
int m = in.nextInt();
int max = 0;
Map<Integer,Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
int num = in.nextInt();
deque.add(num);
if(map.containsKey(num)){
map.put(num, map.get(num)+1);
}
else{
map.put(num, 1);
}
if(deque.size()==m+1){
int remove = (int) deque.remove();
if(map.get(remove)>1){
map.put(remove, map.get(remove)-1);
}
else{
map.remove(remove);
}
}
if(deque.size()==m){
max = max>map.size() ? max:map.size();
}
}
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 →
For each deque if you pass it in a hashset to get the unique set size, it would take time if the size is huge. Instead use a map and for each loop keep track of the occurence of deque numbers.
Here is my code take a look: ---
Scanner in = new Scanner(System.in); ArrayDeque deque = new ArrayDeque<>(); int n = in.nextInt(); int m = in.nextInt(); int max = 0;