Skip to main content
Back to problems
Leetcode
Medium
Arrays
Sliding Window
Two Pointers
Max Consecutive Ones III

Find the longest contiguous subarray of 1s you can obtain by flipping at most kk zeroes.

Acceptance 91%
Problem Statement

Max Consecutive Ones III

You are given a binary array nums and an integer k. You may flip at most k zeroes into ones.

Return the maximum length of a contiguous subarray that contains only 1s after making at most k flips.

The subarray must be contiguous, and you may choose any zeroes within that subarray to flip.

Input Format

  • nums: an array of integers containing only 0 and 1
  • k: an integer representing the maximum number of zeroes you may flip

Output Format

  • Return a single integer: the maximum possible length of a contiguous subarray consisting only of 1s after at most k flips.

Constraints

  • 1 <= nums.length
  • nums[i] is either 0 or 1
  • 0 <= k <= nums.length
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2

Output

6

Explanation

Flip the two zeroes at positions 3 and 4 to get a longest run of six 1s: [1,1,1,1,1,0,1,1,1,1,0]. The best contiguous segment of 1s has length 6.

Example 2

Input

nums = [0,0,1,1,1,0,0], k = 0

Output

3

Explanation

No flips are allowed, so the longest existing run of 1s is [1,1,1], which has length 3.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.