Challenge from LeetCode: count the maximum number of consecutive 1s in a list of 1s and 0s. I got it done pretty quickly, or so I thought. I had not accounted for what would happen upon the last iteration through the for loop. Reworked it and this is what I got:
def checkMax(maxConsec, count):
if count > maxConsec:
return count, 0
else:
return maxConsec, 0
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
maxConsec = 0
count = 0
for index, num in enumerate(nums):
if num == 1:
count += 1
if index+1 == len(nums):
maxConsec, count = checkMax(maxConsec, count)
else:
maxConsec, count = checkMax(maxConsec, count)
return maxConsec
Runtime. Oops. |
I'm sure there are better ways to do this. I thought of putting all my counts in a list and checking for the largest value in the list once the for loop was complete. I wonder if that would make a difference to the runtime and memory usage?
Comments
Post a Comment