import java.util.*;
public class Main {
public static int solution(int[] arr) {
//make a hashmap<key,index> and traverse the array and keep adding key in the hashmap
//if the key repeats that means equal number of 0's,1's & 2's are present
//dont add the updated index of the repeated key as we have to find longest length
int ans = 0;
HashMap<String,Integer> map = new HashMap<>();
int count0 = 0 , count1 =0 , count2 =0 ;
map.put("0#0" ,-1 );
for(int i =0 ;i < arr.length ; i++){
//update counts
if(arr[i] == 0) count0++;
else if(arr[i] == 1) count1++;
else count2++;
//find difference in counts
int diff1 = count1-count0;
int diff2 = count2-count1;
//generate key
String val = diff1 +"#"+diff2;
//if key is already present,dont update the index and find and compare new length with answer
if(map.containsKey(val)){
int len = i - map.get(val);
ans = Math.max(len , ans);
}
else{
map.put(val , i);
}
}
return ans;
}
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scn.nextInt();
}
System.out.println(solution(arr));
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter