Maximum Ones in K Window (Sliding Window)
Given a binary array (containing only 0s and 1s) and a window size k, find the maximum number of 1s that can appear in any subarray of length k.
For example, in [1, 0, 1, 1, 0, 1] with k=3, the windows are: [1,0,1] has 2 ones, [0,1,1] has 2 ones, [1,1,0] has 2 ones, [1,0,1] has 2 ones. Maximum is 2. With k=2, maximum is 1 (from [1,1] at positions 2-3).
This is a classic sliding window problem that maximizes a sum over fixed-size windows. It teaches the sliding window technique for efficiently computing aggregates over all subarrays of fixed length.
The solution computes the sum of the first k elements, then slides the window: subtract the element leaving and add the element entering, tracking the maximum sum seen.
Edge cases include k larger than the array (return 0), an empty array (return 0), and all ones (the maximum is k or the array length, whichever is smaller).
Example Input & Output
Max 2 ones in any window of length 3.
Two 1s in [1,1] and [1,1].
No 1s.
Algorithm Flow

Solution Approach
Use a sliding window to maintain the count of 1s incrementally and track the maximum.
Check edge cases. Compute the sum of the first window. Slide: subtract the outgoing element, add the incoming element, and update the maximum if the current sum exceeds it. Return the maximum sum found.
Time complexity is O(n), space complexity is O(1).
Best Answers
def solution(nums, k):
if len(nums)<k: return 0
ones=sum(nums[:k])
mx=ones
for i in range(k,len(nums)):
ones+=nums[i]-nums[i-k]
if ones>mx: mx=ones
return mxComments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
