525. Contiguous Array
https://leetcode.com/problems/contiguous-array/
Python
Prefix Sum
first_seem
key is difference btw zero_count and one_count, value is the first seem indexfist_seem
inital with0 -> -1
to ensure the first place able to be calculated from next0
s
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
first_seem = {0: -1}
zero_count = 0
one_count = 0
ans = 0
for index, num in enumerate(nums):
if num == 0:
zero_count += 1
else:
one_count += 1
diff = zero_count - one_count
if diff in first_seem:
ans = max(ans, index - first_seem[diff])
else:
first_seem[diff] = index
return ans