Maximum Number of 1s in K Window
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
Algorithm Flow

Solution Approach
Initialize count in first window. Slide: subtract leaving element, add entering element. Track max.
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++)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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
