In this program I'm trying to fetch the elements skipping kth steps inside the array for each element k times.
Also I'm storing the max element inside the arraylist after the iteration is complete for j-for loop.
Although I'm specifying the key as i%k still the element max fetched after every j-itereation gets added to previous key-value pair affecting the values(making it repetitive).
Apparently I found out that if I initialize the arraylist inside the i-for loop then it won't affect the previous added element rather than initializing inside main function. However I'm not sure for the apparent reason for the same
According to me clearing the arraylist doesn't matter the map will always point to the arraylist(named: value) thus changing all the values inside map
CODE
int t = sc.nextInt();
ArrayList<Integer> value = new ArrayList<Integer>();
Map<Integer, ArrayList<Integer>> map = new HashMap<Integer,ArrayList<Integer>>();
while(t-- > 0) {
int length = sc.nextInt(); //length =7
int k = sc.nextInt();
int arr[] = new int[length];
//inserting in an array
for(int i = 0; i<length; i++) {
arr[i] = sc.nextInt();
}
//[4,2,3,6,7,4,3]
//now we are gonna iterate over the array
//also we are going to store the value in (i%k) key
for(int i = 0; i<k; i++) {
value.clear(); //**If i initialize the arraylist here then problem is solved**
int max = Integer.MIN_VALUE;
for(int j = i; j<length; j+=k) {
max = Math.max(max, arr[j]);
System.out.println(max + " "+ i%k);
}
value.clear();
value.add(max);
map.put((i%k), value);
System.out.println(map);
}
}