import java.util.HashMap; public class LongestSubarray { public static int findMaxLength(int[] nums) { // HashMap to store the first occurrence of the prefix sum HashMap map = new HashMap<>(); // Initialize the prefix sum and the result int prefixSum = 0; int maxLength = 0; // Iterate through the array for (int i = 0; i < nums.length; i++) { // If the element is 0, treat it as -1 (this helps balance the 0s and 1s) prefixSum += (nums[i] == 0) ? -1 : 1; // If prefixSum is 0, it means the subarray from index 0 to i has equal 0s and 1s if (prefixSum == 0) { maxLength = i + 1; } // If the prefixSum has been seen before, it means there is a subarray with equal 0s and 1s else if (map.containsKey(prefixSum)) { // Update the max length with the length of the subarray found maxLength = Math.max(maxLength, i - map.get(prefixSum)); } else { // Store the first occurrence of the prefix sum map.put(prefixSum, i); } } return maxLength; } public static void main(String[] args) { int[] nums = {0, 1, 0, 1, 1, 0}; System.out.println("Longest subarray with equal 0s and 1s: " + findMaxLength(nums)); } } ============================================================================ //{ Driver Code Starts //Initial Template for Java import java.util.*; import java.lang.*; import java.lang.*; import java.io.*; class Driverclass { public static void main (String[] args) { Scanner in = new Scanner(System.in); int t= in.nextInt(); while(t-->0){ int n = in.nextInt(); int [] arr= new int[n]; for(int i=0;i hm=new HashMap<>(); hm.put(0,1); int count=0; int sum=0; for(int i=0;i 0) { // Read the entire line containing the array elements String line = br.readLine(); // Split the line into an array of strings, then parse them as integers String[] tokens = line.split("\\s+"); int[] a = new int[tokens.length]; for (int i = 0; i < tokens.length; i++) { a[i] = Integer.parseInt(tokens[i]); } // Create the Solution object Solution obj = new Solution(); // Call maxLen function and print the result System.out.println(obj.maxLen(a)); } } } // } Driver Code Ends class Solution { public int maxLen(int[] arr) { // Your code here HashMap hm=new HashMap<>(); for(int i=0;imaxlen){ maxlen=len; } }else{ hm.put(sum,i); } } return maxlen; } } ===================================================================