-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxSubStringForBinaryString.py
More file actions
49 lines (40 loc) · 1.31 KB
/
MaxSubStringForBinaryString.py
File metadata and controls
49 lines (40 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
all_examples = ["1100011","110111000","1000011", "101011"]
def maxSubArray(binaryString):
if not binaryString:
return []
maxCount = 0
count = 0
startIndex = -1
length = 0
maxLength = 0
ans= []
for i, n in enumerate(binaryString):
if n == '1':
count += 1
else:
count -= 1
length += 1
if startIndex == -1:
# starting the index again after resetting it
startIndex = i
if count > maxCount:
# highest priority of maxCount
maxCount = count
maxLength = length
ans = [binaryString[startIndex:i+1]]
elif count == maxCount and length > maxLength:
# if count matched, select the one with max length
ans = [binaryString[startIndex:i+1]]
maxLength = length
elif count == maxCount and length == maxLength:
# if count and length matches, select both
ans.append(binaryString[startIndex:i+1])
if count < 0:
# resetting the count, length and startIndex when count goes negative
count = 0
length = 0
startIndex = -1
return ans
for s in all_examples:
x = maxSubArray(s)
print(s, x)