Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
from collections import Counter class Solution: def longestOnes(self, nums: L...

Austin McDaniel

Nov 4, 2022

from collections import Counter class Solution: def longestOnes(self, nums: List[int], k: int) -> int:

max_ones = 0 w_start = 0 bit_count = Counter() bit_count[0] = 0

for w_end in range(len(nums)):

bit_count[nums[w_end]] += 1

if w_end - w_start + 1 - bit_count[1] > k: bit_count[nums[w_start]] -= 1 w_start +=1 else: max_ones = max(w_end - w_start + 1, max_ones)

return max_ones

I believe this is a more intuitive solution. The idea is that we're seeing the difference between the window size and the thing we are trying to maximize. In this case we are trying to maximize 1s, and that difference must be bigger than the allowed amount of replacements otherwise we have too many replacements and must decrement out window size. The only difference between this problem and the letter problem is in this one we know what exactly we are trying to maximize, and in the letters problem we are not exactly sure which letter we're maximizing from a programatic POV we're just making sure that the max_char is taking up more space in the array than the allowed space for replacements.

0

0

Comments
Comments

On this page