1004.Max Consecutive Ones 3
My code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
def longestOnes(self, nums: List[int], k: int) -> int:
start = end = 0
max_count = count = 0
while end < len(nums):
if nums[end] == 1:
end += 1
count += 1
elif nums[end] == 0 and k > 0:
end += 1
k -= 1
count += 1
else:
while nums[start] == 1:
start += 1
count -= 1
start += 1
end += 1
max_count = max(max_count,count)
return max_count
1
2
Runtime : 516ms (beats 64.17%)
Memory : 17.07MB (beats 74.84%)
Other code
1
2
3
4
5
6
7
8
9
10
11
class Solution:
def longestOnes(self, nums: List[int], k: int) -> int:
l=r=0
for r in range(len(nums)):
if nums[r] == 0:
k-=1
if k<0:
if nums[l] == 0:
k+=1
l+=1
return r-l+1
1
2
Runtime : 461ms (beats 94.37%)
Memory : 16.79MB (beats 99.74%)