Let me add some explanation.

If we keep track of the total count of ones and zeros from 0 to len - 1, then to valid whether the subarray from i to j is valid, we just have to check if ones[j] - ones[i - 1] == zeros[j] - zeros[i - 1].

Naively it will take O(N^2) to compute. But that equation is the same as ones[j] - zeros[j] == one[i - 1] - zeros[i - 1], and it is diff[j] == diff[i - 1], then we can use hashmap to reduce the time complexity to O(N).

Here is my implementation:

public class Solution {
public int findMaxLength(int[] nums) {
HashMap<Integer, Integer> diff2idx = new HashMap<>();
int res = 0;
int diff = 0;
diff2idx.put(0, -1);
int ones = 0;
for (int i = 0; i < nums.length; i++) {
ones += nums[i];
diff = ones - (i + 1 - ones); // ones - zeros
if (diff2idx.containsKey(diff)) {
res = Math.max(res, i - diff2idx.get(diff));
} else {
diff2idx.put(diff, i);
}
}
return res;
}
}