It can be further simplified by using just one number to record the number of diffs

zero > 0 means we have more zeros than ones

zero < 0 means we have more ones than zeros

zero == 0 means we have equal number of ones and zeros

For example, if at any index i we have zero = 1, then we have 1 diff (1 more 0s than 1s), we record it in the HashMap, and if later at index j we meet another situation that zero = 1, this means from the index i till the index j, the number of 0s and 1s are the same.

public class Solution {
public int findMaxLength(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
int max = 0;
int zero = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) zero++;
else zero--;
if (zero == 0) max = i + 1;
if (!map.containsKey(zero)) map.put(zero, i);
else max = Math.max(max, i - map.get(zero));
}
return max;
}
}