Write the complete Java code and explain the code Remove all errors from this code
Write the complete Java code and explain the code
Remove all errors from this code
import java.util.*;
import java.io.*;
class Main {
public static void main(String args[]) {
// taking input using class Scanner
Scanner sc = new Scanner(System.in);
// taking total count of testcases
int t = sc.nextInt();
while (t-- > 0) {
// taking size of subArrays
int k = sc.nextInt();
// Declaring and Intializing an array of size n
int arr[] = new int[n];
// adding all the elements to the array
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// Calling the method max_of_subarrays of class solve
// and storing the result in an ArrayList
ArrayList<Integer> res = new Solution().max_of_subarrays(arr, n, k);
// printing the elements of the ArrayList
for (int i = 0; i < res.size(); i++)
System.out.print(res.get(i) + " ");
System.out.println();
}
}
}
class Solution {
static ArrayList<Integer> max_of_subarrays(int arr[], int n, int k) {
TreeMap<Integer> map=new TreeMap<>();
for(int i=0;i<k; ){
map.put(arr[i],map.getOrDefault(arr[i],0)+1);
}
ArrayList<Integer> ;
ans.add(map.lastKey());
for(int i=k;i<n;i++){
map.get(arr[i-k])-1);
if (map.get(arr[i-k])==0)
map.remove(arr[i-k]);
map.put(arr[i],map.getOrDefault(arr[i],0)+1);
ans.add(map.lastKey());
}
return ans
}
}
Step by step
Solved in 3 steps with 1 images