I'm given N integers. I need to find the maximum number of unique integers among all the possible contiguous subarrays of size M.
Scanner in = new Scanner(System.in);
Deque deque = new ArrayDeque<Integer>();
int n = in.nextInt();
int m = in.nextInt();
in.nextLine();
String s = in.nextLine();
in.close();
int maxUnique = 0;
List<Integer> numbers = Stream.of(s.split(" "))
.map(Integer::parseInt)
.collect(Collectors.toList());
for (int i = 0; i <= n-m; i++) {
HashSet<Integer> unique = new HashSet<>(numbers.subList(i, i+m));
if (maxUnique < unique.size())
maxUnique = unique.size();
if (maxUnique == m) {
System.out.println(maxUnique);
return;
}
}
System.out.println(maxUnique);
It works fine, but fails on big arrays due to timeout. For example N=100000, M=98777 times out.
How can I improve it?