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.
I have a solution optimized
import java.util.*;
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Deque deque = new ArrayDeque<>();
int n = in.nextInt();
int m = in.nextInt();
int max = 0;
Set set = new LinkedHashSet<>();
for (int i = 0; i < n; i++) {
int num = in.nextInt();
deque.addLast(num);
set.add(num);
if (deque.size()==m){
//updtae max
if(set.size()>max){
max = set.size();
}
int first = deque.getFirst();
deque.removeFirst();
if(!deque.contains(first)){
set.remove(first);
}
}
}
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 →
I have a solution optimized
import java.util.*; public class test { public static void main(String[] args) { Scanner in = new Scanner(System.in); Deque deque = new ArrayDeque<>(); int n = in.nextInt(); int m = in.nextInt(); int max = 0; Set set = new LinkedHashSet<>(); for (int i = 0; i < n; i++) { int num = in.nextInt(); deque.addLast(num); set.add(num); if (deque.size()==m){ //updtae max if(set.size()>max){ max = set.size(); } int first = deque.getFirst(); deque.removeFirst(); if(!deque.contains(first)){ set.remove(first); }