| class Solution: | |||||
| def findMaxLength(self, nums): | |||||
| result = [] | |||||
| current = 0 | |||||
| for n in nums: | |||||
| if n == 0: | |||||
| current -= 1 | |||||
| else: | |||||
| current += 1 | |||||
| result.append(current) | |||||
| hm = dict() | |||||
| hm[0] = [-1, None] | |||||
| for ind, val in enumerate(result): | |||||
| if val in hm: | |||||
| hm[val][1] = ind | |||||
| else: | |||||
| hm[val] = [ind, None] | |||||
| maxLength = 0 | |||||
| for key, value in hm.items(): | |||||
| if value[1] is not None: | |||||
| new = value[1] - value[0] | |||||
| if new > maxLength: | |||||
| maxLength = new | |||||
| return maxLength | |||||
| s = Solution() | |||||
| print("Expected: 2") | |||||
| print("Got:", s.findMaxLength([1, 0])) |
| Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. | |||||
| Example 1: | |||||
| Input: [0,1] | |||||
| Output: 2 | |||||
| Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. | |||||
| Example 2: | |||||
| Input: [0,1,0] | |||||
| Output: 2 | |||||
| Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. | |||||
| Note: The length of the given binary array will not exceed 50,000. |
| #!/bin/bash | |||||
| python3 main.py |