1004. Maximum number of consecutive 1s III
Given an array A consisting of several 0s and 1, we can change up to K values from 0 to 1.
Returns the length of the longest (contiguous) sub-array containing only 1.
Example 1:
输入:A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
输出:6
解释:
[1,1,1,0,0,1,1,1,1,1,1]
粗体数字从 0 翻转到 1,最长的子数组长度为 6。
Example 2:
输入:A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
输出:10
解释:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
粗体数字从 0 翻转到 1,最长的子数组长度为 10。
prompt:
- 1 <= A.length <= 20000
- 0 <= K <= A.length
- A[i] is 0 or 1
Method one: sliding window
Problem-solving ideas
- Double pointer still
[left, right)
sliding window simulation right
Traverse the pointer to the right, when encounteringK
a0
time, the value of the calculation resultret = max(ret, right - left)
and movesleft
the pointer to the next0
right .
Reference Code
public int longestOnes(int[] A, int K) {
int n = A.length;
int ret = 0;
int left = 0, right = 0, count = 0;
while (right < n) {
if (A[right] == 0) {
if (count < K) {
count++;
} else {
ret = Math.max(ret, right - left);
do {
left++;
} while (A[left - 1] == 1);
}
}
right++;
}
return Math.max(ret, right - left);
}
Results of the
- Time complexity: O(n)
- Space complexity: O(1)