525. Contiguous Array

Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.



def findMaxLength(self, nums: List[int]):
       
    indices = {0:-1}
   
    L = len(nums)
    max_len = 0
   
    polarity = 0
   
    for i in range(L):
        polarity = polarity-1 if nums[i] == 0 else polarity + 1
        if polarity in indices:
            max_len = max(max_len, i - indices[polarity])
        else:
            indices[polarity] = i
           
    return max_len

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break