525. Contiguous Array
https://leetcode.com/problems/contiguous-array/
Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.Thoughts
Code
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
presum = {0: -1}
s = res = 0
for i, v in enumerate(nums):
s += 1 if v == 1 else -1
if s not in presum:
presum[s] = i
else:
res = max(res, i - presum[s])
return res
Analysis
Last updated