Max Consecutive Ones III

Given a binary array `nums` and an integer `k`, return the maximum number of consecutive `1`s in the array if you can flip at most `k` `0`s to `1`s.

30:00

Max Consecutive Ones III
medium
Free written solution
Topics
Companies

Given a binary array nums and an integer k, return the maximum number of consecutive 1s in the array if you can flip at most k 0s to 1s.

Example 1:
Input: {"nums":[1,1,1,0,0,0,1,1,1,1,0],"k":2}
Output: 6
Constraints:
  • 1≤nums.length≤1051 \leq \text{nums.length} \leq 10^5

  • nums[i]\text{nums}[i] is either 00 or 11

  • 0≤k≤nums.length0 \leq k \leq \text{nums.length}

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,1,1,0,0,0,1,1,1,1,0],"k":2}

Grow a window from the left. It may hold at most k = 2 zeros, which we pretend are flipped to 1.

flip budget: 0 of 2 used

nums

1

0

1

1

1

2

0

3

0

4

0

5

1

6

1

7

1

8

1

9

0

10

window

0

zeros in window

0

best

0

Variables
VariableValue
left0
zeros0
best0
k2
DepthFunction Call
Stack empty
0/30