I am practicing two pointers techniques to solve Max Consecutive Ones - LeetCode
Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
Input: [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.
Note:
- The input array will only contain
0
and1
.- The length of input array is a positive integer and will not exceed 10,000
The solution use Kadane algorithms
class Solution:
def findMaxConsecutiveOnes(self, nums: "List[int]") -> int:
loc_max = glo_max = 0
for i in range(len(nums)):
if nums[i] == 1:
loc_max += 1
elif nums[i] != 1:
glo_max = max(glo_max, loc_max)
loc_max = 0
#in case of the corner case [.....,1 ,1, 1]
return max(glo_max, loc_max)
The problem with the solution is that it's not a decent two pointers solution with slow and fast pointer.(It did not an explicit slow pointer)
A intuitive idea to employ slow pointer is to take a slow pointer to remember the starting index of consecutive ones, when fast pointer reach a non-one, the relation is length= fast - slow
.
However, it is difficult to locate slow pointing to a first One. [0, 0, 0, 1, 1, 1, 1]
,
As a comprised proposal, re-define slow to the forward non-One of a ones array,when fast reach to another non-One. Use relation: length = fast -slow + 1
class Solution:
def findMaxConsecutiveOnes(self, nums: "List[int]") -> int:
"""
#1Sort####
##2Strategy######
CP: two pointers
RU: res = fast - slow
"""
###3Solve######
slow, fast, glo_max = 0, 0, 0
for fast in range(len(nums)):
if nums[fast] != 1: #stop
loc_max = fast -slow + 1
glo_max = max(glo_max, loc_max)
slow = fast
return max(loc_max, glo_max)
####4Check#########################
#[0, 0,1, 0, 1, 1]
I tried and debugged multiple times to define slow as the first index of Ones sub-array, did not get the desired result.
Could you please give any hints for that solution.