Given a binary array
nums, return the maximum number of consecutive 1’s in the array.
Input: nums = [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
Input: nums = [1,0,1,1,0,1] Output: 2
We iterate through the array and use a counter variable that increments every time we see number 1, and if we see number 0, we’ll reset that counter, but we also keep track of the maximum value that the counter variable has stored, and that will be the answer.
Time: O(n) to loop through all elements in the array
Space: O(1) for the tracking variables and references in the loop
class Solution: def findMaxConsecutiveOnes(self, nums): maxSoFar = 0 oneCounter = 0 for e in nums: if e == 1: oneCounter += 1 maxSoFar = max(maxSoFar, oneCounter) else: # 0 oneCounter = 0 return maxSoFar solution = Solution() assert(solution.findMaxConsecutiveOnes([1,1,0,1,1,1]) == 3) assert(solution.findMaxConsecutiveOnes([1,0,1,1,0,1]) == 2) print('Passed all test cases')
Creator and author at DEPHONY. I develop open-source/free software and write technical tutorials that are straight to the point to save readers’ time to learn and apply. Support my work by becoming a Patron 🙂