Max Consecutive Ones III
Sliding Window
Problem
Given an array A
of 0s and 1s, we may change up to K
values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
For example:
Thought Process
It is a similar approach to Longest Repeating Character Replacement
Following a similar approach, we'll iterate through the array to add one number at a time in the window. We'll also keep track of the maximum number of repeating 1s in the current window (maxOnesCount). So at any time, we know that we can have a window with 1s repeating 'maxOnesCount' times, so we should try to replace the remaining 0s. If we have more thank 'k' remaining 0s, we should shrink the window as we are not allowed to replace more than 'k' 0s.
Solution
Key Points
Keeping count of maximum number of 1s within the window and applying the approach we usedin Longest Repeating Character Replacement
We're finding the number of zeroes we have within our window to see if that number is greater than 'K'. If so, we need to shrink our window.
Time Complexity
Time:
Space:
Last updated
Was this helpful?