给出一个0-1数列,问去掉一个元素,最多有多少个连续的1
预处理每个连续的0和1有几个,若开头和结尾是0的话补上0个1
#1493
#Runtime: 322 ms (Beats 65.73%)
#Memory: 17.6 MB (Beats 31.25%)
class Solution(object):
def longestSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
one = []
zero = []
ans = 0
t0, t1 = 0, 0
if not nums[0]:
one.append(0)
for j in range(0, len(nums)):
if nums[j]:
if j == 0 or nums[j - 1]:
t1 += 1
else:
if t0:
zero.append(t0)
t1 = 1
t0 = 0
else:
if j == 0 or nums[j - 1] == 0:
t0 += 1
else:
if t1:
one.append(t1)
t1 = 0
t0 = 1
if t1:
one.append(t1)
if t0:
zero.append(t0)
one.append(0)
if not len(zero):
return one[0] - 1
for i in range(0, len(one)):
if i and zero[i - 1] == 1:
ans = max(ans, one[i - 1] + one[i])
else:
ans = max(ans, one[i])
return ans