fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. Scanner sc = new Scanner(System.in);
  13. int size = sc.nextInt();
  14.  
  15. int[] arr =new int[size];
  16.  
  17. for(int i = 0;i<size;i++){
  18. arr[i] = sc.nextInt();
  19. }
  20.  
  21. int result = maxLen(arr);
  22. System.out.println(result);
  23.  
  24. }
  25. public static int maxLen(int[] arr) {
  26.  
  27. HashMap<Integer, Integer> present = new HashMap<>();
  28.  
  29. present.put(0, -1);
  30.  
  31. int sum = 0;
  32. int maxLongestSubArray = 0;
  33.  
  34. for (int i = 0; i < arr.length; i++) {
  35.  
  36. sum += (arr[i] == 0) ? -1 : 1;
  37.  
  38. if (present.containsKey(sum)) {
  39. int currentLongestSubArray = i - present.get(sum);
  40. maxLongestSubArray = Math.max(currentLongestSubArray, maxLongestSubArray);
  41. } else {
  42. present.put(sum, i);
  43. }
  44. }
  45.  
  46. return maxLongestSubArray;
  47. }
  48. }
Success #stdin #stdout 0.1s 54488KB
stdin
7
0 1 1 0 1 1 0 
stdout
4