487 Max Consecutive Ones II
Input: [1,0,1,1,0]
Output: 4
Explanation: Flip the first zero will get the the maximum number of consecutive 1s.
After flipping, the maximum number of consecutive 1s is 4.class Solution:
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
def count_ones(start, end, incr):
d = {}
ones = 0
for i in range(start, end, incr):
num = nums[i]
if num:
ones += 1
else:
d[i] = ones
ones = 0
return d
# hash number of ones to the left of zeros
# hash number of ones to the right of zero
hash_left = count_ones(0, len(nums), 1)
hash_right = count_ones(len(nums) - 1, -1, -1)
if not hash_left:
return len(nums)
# iterate through nums and return the max
# of (left + right) if the number is zero
max_ones = 0
for left_i, left_ones in hash_left.items():
# add one to be inclusive of the bit we flipped
max_ones = max(max_ones, left_ones + hash_right[left_i] + 1)
return max_onesLast updated