```
public int FindMaxLength(int[] nums) {
Dictionary<int, int> firstidx = new Dictionary<int, int>();
int max = 0, sum = 0;
firstidx[0] = -1;
for(int i = 0; i < nums.Length; i++) {
sum += nums[i] == 0 ? -1 : 1;
if (firstidx.ContainsKey(sum)) {
max = Math.Max(max, i - firstidx[sum]);
} else {
firstidx[sum] = i;
}
}
return max;
}
```