import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型ArrayList
* @return int整型
*/
public int findMaxLength(ArrayList<Integer> nums) {
int[] pre = new int[nums.size()];
pre[0] = nums.get(0) == 0 ? -1 : 1;
for (int i = 1; i < nums.size(); i++) {
if (nums.get(i) == 0) {
pre[i] = pre[i - 1] - 1;
} else {
pre[i] = pre[i - 1] + 1;
}
}
int res = 0;
HashMap<Integer, Integer> hashMap = new HashMap<>();
// [i, j] 范围的子数组的和为 pre[j] - pre[i - 1]
// [i, j] 范围的子数组长度为 j - i + 1
for (int i = 0; i < pre.length; i++) {
if (pre[i] == 0) {
res = Math.max(res, i + 1);
} else {
int previousIndex = hashMap.getOrDefault(pre[i], -1);
if (previousIndex != -1) {
res = Math.max(res, i - previousIndex);
} else {
hashMap.put(pre[i], i);
}
}
}
return res;
}
}