Code Logo

Maximum Number of 1s in K Window

Published at24 Jul 2026
Easy 2 views
Like0

Given a binary array (containing only 0s and 1s) and a window size k, find the maximum number of 1s in any contiguous subarray of length k using the sliding window technique.

Maintain a running count of 1s in the current window. Start by counting 1s in the first k elements. Then slide the window one position at a time: when a 0 enters and a 1 leaves (or vice versa), update the count accordingly. Track the maximum count seen across all windows.

The sliding window approach is O(n) time and O(1) space. Each element is visited exactly twice — once when it enters the window and once when it leaves — making this highly efficient for large arrays.

Edge cases include empty arrays (return 0), k larger than the array (return 0), and arrays with all 0s (return 0).

This problem demonstrates the classic sliding window pattern for binary properties where the window state can be maintained with a simple counter.

The sliding window sum approach works because addition/subtraction of boundary elements correctly maintains the window sum without recalculating from scratch. This is the most efficient approach for fixed-size window problems on arrays. The sliding window sum approach works because addition/subtraction of boundary elements correctly maintains the window sum without recalculating from scratch. This is the most efficient approach for fixed-size window problems on arrays.

Example Input & Output

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

Algorithm Flow

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

Solution Approach

Initialize count in first window. Slide: subtract leaving element, add entering element. 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++)c+=nums[i];
        int m=c;
        for(int i=k;i<nums.length;i++){c+=nums[i]-nums[i-k];if(c>m)m=c;}
        return m;
    }
}