Optimal: −1/+1 prefix sums with first-seen indexes
Time O(n) Space O(n)Running sum adds +1 for a 1 and −1 for a 0. If sum at index j was first seen at index i, then nums[i+1..j] is balanced, with length j − i. Seed the map with sum 0 at index −1.
nums = [0, 1, 0]first index of sum(map)
State(vars)
Step 1/4Seed: sum 0 at index −1.
import java.util.HashMap;
import java.util.Map;
class Solution {
public int findMaxLength(int[] nums) {
Map<Integer, Integer> first = new HashMap<>();
first.put(0, -1);
int sum = 0, best = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i] == 1 ? 1 : -1;
Integer j = first.get(sum);
if (j != null) best = Math.max(best, i - j);
else first.put(sum, i); // keep only the first index
}
return best;
}
}Verdict: One pass.