Maximum Number of 0s in K Window
Given a binary array and window size k, find the maximum number of 0s in any contiguous subarray of length k using sliding window.
Maintain a counter of zeros in the current window. Count zeros in the first k elements, then slide through the array. When a zero enters the window, increment the counter. When a zero leaves, decrement it. Track the maximum zero count.
This is the complement of the max-ones problem and uses the same sliding window pattern. The counter tracks how many elements in the current window satisfy the condition (being zero).
Time complexity is O(n) with O(1) extra space. Each element contributes to exactly one increment and one decrement over the entire algorithm.
Edge cases include empty arrays, k larger than array length, and arrays with all 1s where the maximum zero count is 0.
The zero-counting approach tracks a condition counter that adjusts by at most 2 per slide (one decrement for leaving, one increment for entering). This O(n) approach is optimal as each element is processed in constant time. The zero-counting approach tracks a condition counter that adjusts by at most 2 per slide (one decrement for leaving, one increment for entering). This O(n) approach is optimal as each element is processed in constant time. The maximum zero count is the complement of the minimum one count in any fixed window.
Example Input & Output
Algorithm Flow
Solution Approach
Find the maximum number of zeros in any subarray of size k. Use a sliding window to count zeros incrementally. Maintain a zero count for the current window; when sliding, decrement if the outgoing element is 0 and increment if the incoming is 0. Track the maximum count.
The sliding window avoids O(k) recomputation for each window, reducing time from O(n*k) to O(n).
Time O(n), Space O(1).
Best Answers
class Solution {
public int solution(int[] nums, int k) {
if (nums.length<k) return 0;
int c=0;for(int i=0;i<k;i++)if(nums[i]==0)c++;
int m=c;
for(int i=k;i<nums.length;i++){if(nums[i-k]==0)c--;if(nums[i]==0)c++;if(c>m)m=c;}
return m;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
