Code Logo

Maximum Ones in K Window (Sliding Window)

Published at24 Jul 2026
Easy 0 views
Like0

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

Example 1
Input
[1],1
Output
1
Example 2
Input
[1,0,1,0,1],3
Output
2
Explanation

Max 2 ones in any window of length 3.

Example 3
Input
[1,1,1,0],2
Output
2
Explanation

Two 1s in [1,1] and [1,1].

Example 4
Input
[0,0,0],2
Output
0
Explanation

No 1s.

Example 5
Input
[],2
Output
0

Algorithm Flow

Recommendation Algorithm Flow for Maximum Ones in K Window (Sliding Window)
Recommendation Algorithm Flow for Maximum Ones in K Window (Sliding Window)

Solution Approach

Use a sliding window to maintain the count of 1s incrementally and track the maximum.

function maxOnes(arr, k)
  if k > length(arr) or length(arr) == 0 then return 0
  sum = 0, maxSum = 0
  for i = 0 to k - 1
    sum = sum + arr[i]
  maxSum = sum
  for i = k to length(arr) - 1
    sum = sum - arr[i - k] + arr[i]
    if sum > maxSum then maxSum = sum
  return maxSum

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

python
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 mx