The problem context involves working with data structures in Java, specifically Deque and HashSet. The task is to find the maximum number of unique numbers in all possible subarrays of a specific size from an array. The array and the size of the subarrays are provided as input.
CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷
The solution approach involves using a Deque to store the elements of the subarray and a HashSet to store the unique elements. For each element in the array, it is added to the Deque and HashSet. When the size of the Deque equals the size of the subarray, the size of the HashSet (which represents the number of unique elements) is compared with the current maximum. The first element of the Deque is then removed. If this element is not in the Deque anymore, it is also removed from the HashSet. This process continues until all elements in the array have been processed. The maximum number of unique elements found is then printed.
/**
*
*/
package com.javaaid.hackerrank.solutions.languages.java.datastructures;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.Scanner;
/**
*
*/
public class JavaDequeue {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Deque dq = new ArrayDeque();
HashSet s = new HashSet();
int n = sc.nextInt();
int m = sc.nextInt();
int max = 0;
for (int i = 0; i < n; i++) {
int tmp = sc.nextInt();
dq.add(tmp);
s.add(tmp);
if (dq.size() == m) {
max = Math.max(s.size(), max);
int item = dq.remove();
if (!dq.contains(item)) {
s.remove(item);
}
}
}
System.out.println(max);
sc.close();
}
}
If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.
AI is here now, and other candidates might be using it to get ahead and win the job. 🧐
The form has been successfully submitted.