Max Consecutive Ones III

Sliding Window / 2 Pointer Longest and Smallest Window Problems Hard
  • Fun Fact: This programming problem is a pragmatic application of the "sliding window" concept used in fields like video streaming and networking protocols
  • By controlling the number of bits that can be flipped in a buffer (representing data or packets), developers can optimize data loss or error handling
  • Algorithms like these help smooth your Netflix binges, ensuring your video doesn't stutter even if some data packets arrive out of order or get lost!

Given a binary array nums and an integer k, flip at most k 0's.

Return the maximum number of consecutive 1's after performing the flipping operation.

Examples:

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

Output : 10

Explanation : The maximum number of consecutive 1's are obtained only if we flip the 0's present at position 3, 4, 5 (0 base indexing).

The array after flipping becomes [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0].

The number of consecutive 1's is 10.

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

Output : 9

Explanation : The underlines 1's are obtained by flipping 0's in the new array.

[1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1].

The number of consecutive 1's is 9.

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

Constraints

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 1
  • 0 <= k <= nums.length

Hints

  • "Use a sliding window to maintain a range of elements where at most k 0s are flipped into 1s. Keep a counter for the number of 0s in the current window. When the counter exceeds k, move the left pointer forward while decrementing the count of 0s if the leftmost element is 0."
  • "At each step, calculate the length of the current valid window as right−left+1. Update the maximum length whenever a larger valid window is found. "

Company Tags

Roche American Express HCL Technologies JPMorgan Chase Target Zoho Etsy Walmart eBay Zomato Red Hat Unity Technologies NVIDIA Splunk Morgan Stanley Lyft ARM Byju's Reddit Goldman Sachs Epic Games Instacart KPMG IBM Chewy Google Microsoft Amazon Meta Apple Netflix Adobe