Intermediate Level

Implement the maxConsecutiveOnesWithKFlips method that returns the longest run of 1 values after flipping at most k zeroes.

The input contains a binary array nums, its length size, and an integer k. You may flip at most k zeroes into ones.

Your task is to return the maximum number of consecutive ones possible after performing at most k flips.

For example, in [1,1,1,0,0,0,1,1,1,1,0] with k = 2, the longest possible run has length 6.

Example 1

Input
nums (int[]) = [1,1,1,0,0,0,1,1,1,1,0]
size (int) = 11
k (int) = 2
Returns (int) 6

Example 2

Input
nums (int[]) = [0,0,1,1,1,0,0]
size (int) = 7
k (int) = 0
Returns (int) 3

Example 3

Input
nums (int[]) = [0,0,0]
size (int) = 3
k (int) = 2
Returns (int) 2

Use a sliding window that keeps at most k zeroes.

Move the right pointer across the array and count zeroes inside the window. If the zero count becomes greater than k, move the left pointer until the window is valid again.

The largest valid window length is the answer.

Pseudocode:

function maxConsecutiveOnesWithKFlips(nums, size, k):
    left = 0
    zeroCount = 0
    best = 0
    for right from 0 to size - 1:
        if nums[right] == 0:
            zeroCount++
        while zeroCount > k:
            if nums[left] == 0:
                zeroCount--
            left++
        best = maximum(best, right - left + 1)
    return best
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.