class Solution {
public int findMaxLength(int[] nums) {
Map<Integer,Integer> map = new HashMap<>();
map.put(0,-1);
int sum=0,maxLen=0;
for(int i=0;i<nums.length;i++){
sum += nums[i]==0?-1:1;
if(map.containsKey(sum)) maxLen = Math.max(maxLen,i-map.get(sum));
else map.put(sum,i);
}
return maxLen;
}
}
Explanation: Prefix sum method with 0 as -1. HashMap stores earliest index for each sum. Difference gives max length subarray with equal 0s and 1s.
β± O(n) | πΎ O(n)