1004. Max Consecutive Ones III
- Max Consecutive Ones III python solution
題目描述
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.
解析
連續的子數組裏面,最多可以變換K個0,可以等價於一個[i,j]的窗口裏面的0的個數小於K個。
如果窗口[i,j]裏面的0的個數小於K個,那麼這個窗口一定是合法。
如果窗口[i,j]裏面的0的個數已經大於K個了,那麼這個窗口就不合法,我們需要把i向前推進,直到窗口裏面的0的個數小於K個。
所以i只有在窗口內0的個數不滿足要求時纔會推進,j是一直推進的。在這個過程中,窗口的長度是不會減小的。會先增大到最佳長度,然後不變,直到最後結束。
class Solution:
def longestOnes(self, A, K):
res = i = 0
for j in range(len(A)):
K -= A[j] == 0
if K < 0:
K += A[i] == 0
i += 1
res = j - i + 1
return res
Reference
https://leetcode.com/problems/max-consecutive-ones-iii/discuss/247564/JavaC%2B%2BPython-Sliding-Window