Skip to content

Commit 4994a72

Browse files
committed
Solution Uploaded.
1 parent fca2e19 commit 4994a72

File tree

1 file changed

+29
-0
lines changed
  • 30 Days Challange/Week 2/6. Contiguous Array

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
3+
4+
Example 1:
5+
Input: [0,1]
6+
Output: 2
7+
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
8+
Example 2:
9+
Input: [0,1,0]
10+
Output: 2
11+
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
12+
Note: The length of the given binary array will not exceed 50,000.
13+
"""
14+
class Solution:
15+
def findMaxLength(self, nums: List[int]) -> int:
16+
result, total, hmap = 0,0,{}
17+
for i in range(len(nums)):
18+
if nums[i] == 0:
19+
total -= 1
20+
else:
21+
total += 1
22+
if total == 0:
23+
result = i + 1
24+
if total not in hmap:
25+
hmap[total] = i
26+
else:
27+
if i - hmap[total] > result:
28+
result = i - hmap[total]
29+
return result

0 commit comments

Comments
 (0)