Hi programmers !
when solving problems you'll often need to calculate the maximum number of consecutive occurrence of an element in a string, for our article we'll do it for occurrences of 1's and 0's.
First method : we'll just travers the array from left to right. I f we see a zero ( or one ) , we will increment count and compare it the maximum so far. If we see a 1 ( or 0 ), we will reset count to 0.
the code in python is :
def getMaxZeros(s):
array = list(s)
# initialize count
count = 0
# initialize max
result = 0
for i in range(0, len(array)):
# Reset count when 0 is found
if (array[i] == 0):
count = 0
# If 1 is found, increment count
# and update result if count
# becomes more.
else:
# increase count
count += 1
result = max(result, count)
return result
Second method : we'll use the findall method from the ru module.
the code in python is :
import re
def getMaxzeros(b):
return len(max(re.findall(r"0+", b)))
sources :
Maximum consecutive one’s (or zeros) in a binary array - GeeksforGeeks
Clash of Code - Clash results (codingame.com)
I hope that you found this article interesting, thanks.
![]() |
0 Comments