Code Logo

Maximum Number of 0s in K Window

Published at24 Jul 2026
Easy 0 views
Like0

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

Example 1
Input
[1],1
Output
0
Example 2
Input
[1,0,1,0,1],3
Output
2
Example 3
Input
[0,0,0,1],2
Output
2
Example 4
Input
[1,1,1],2
Output
0
Example 5
Input
[],2
Output
0

Algorithm Flow

Recommendation Algorithm Flow for Maximum Number of 0s in K Window
Recommendation Algorithm Flow for Maximum Number of 0s in K Window

Solution Approach

Count zeros in first window. Slide: adjust for leaving/entering zeros. Track max.

Best Answers

java
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;
    }
}