- Max Consecutive Ones III Medium
356
7
Favorite
Share Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2 Output: 6 Explanation: [1,1,1,0,0,1,1,1,1,1,1] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3 Output: 10 Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000 0 <= K <= A.length A[i] is 0 or 1
思路:活动窗口(Sliding Window)解法,时间复杂度O(n)
代码:python3
class Solution:
def longestOnes(self, A, K) :
left=0
numMax=0
numK=0
for i in range(len(A)):
if A[i] == 0:
numK=numK+1
while numK>K:
if A[left]==1:
left=left+1
else:
left=left+1
numK=numK-1
numMax = max(numMax,i-left+1)
return numMax