Skip to content

Commit 41cf136

Browse files
authored
Create contiguous-array.py
1 parent 5935774 commit 41cf136

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Python/contiguous-array.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
# Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
5+
#
6+
# Example 1:
7+
# Input: [0,1]
8+
# Output: 2
9+
# Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
10+
# Example 2:
11+
# Input: [0,1,0]
12+
# Output: 2
13+
# Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
14+
# Note: The length of the given binary array will not exceed 50,000.
15+
16+
class Solution(object):
17+
def findMaxLength(self, nums):
18+
"""
19+
:type nums: List[int]
20+
:rtype: int
21+
"""
22+
result, count = 0, 0
23+
lookup = {0: 0}
24+
25+
for i, num in enumerate(nums):
26+
count += 1 if num == 1 else -1
27+
if count in lookup:
28+
result = max(result, i+1 - lookup[count])
29+
else:
30+
lookup[count] = i+1
31+
32+
return result

0 commit comments

Comments
 (0)