Max Consecutive Ones III
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
You may flip at most k zeros to ones. Find the longest stretch of ones you can get.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1What does a valid window look like?
- Hint 2Count the zeros in the window; if the count goes above k, shrink from the left.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
A corridor has bulbs, some on (1) and some fused (0). You have k spare bulbs to replace fused ones. What is the longest stretch of corridor you can light up completely? Walk along; every fused bulb you pass uses one spare. When you run out of spares, move your starting point forward past the oldest fused bulb to get that spare back.
- The obvious way
Try every sub-list and count its zeros: O(n²).
- The key insight
A window is fixable when it contains at most k zeros. Extend on the right; whenever the zero count passes k, move the left edge forward until the count is back to k (a zero leaving gives a spare back). The window length at every step is a candidate answer.
- The algorithm
- Zero count = 0, left edge at the start, best = 0.
- Take the next number on the right; if it is 0, zero count + 1.
- Zero count above k? Move the left edge forward (subtract a zero when you pass one) until it is k again.
- Best = the longest window length seen.
Watch it run
Examplebulbs = [1,1,1,0,0,0,1,1,1,1,0], k = 2
Walk along: three lit bulbs, then two fused ones use both spares. Window length 5.
zeros used 2, best 5
Where people slip
- Only decrement the zero count when the number leaving the window is a zero.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def longest_ones(nums, k):
left = 0
zeros = 0 # spares currently in use
best = 0
for right, number in enumerate(nums):
if number == 0:
zeros += 1
while zeros > k: # out of spares: shrink from the left
if nums[left] == 0:
zeros -= 1
left += 1
best = max(best, right - left + 1)
return bestNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.