Max Consecutive Ones III

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

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.

Examples

Example 1:

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

Output: 6

Explanation: Flip the zeros at indices 5 and 10 (or other combinations). The longest subarray of all 1's has length 6, for example [0,0,1,1,1,1,0] after flipping becomes [1,1,1,1,1,1].

Example 2:

Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3

Output: 10

Explanation: Flip the zeros at indices 4, 5, and 9. The longest subarray of all 1's has length 10, from index 2 to index 11.

Example 3:

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

Output: 4

Explanation: The array already has all 1's. No flips needed.

Constraints

  • 1 <= nums.length <= 10^5
  • nums[i] is either 0 or 1
  • 0 <= k <= nums.length
Source: Sliding Window pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle