Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import deque
- class Solution:
- def longestOnes(self, A: List[int], K: int) -> int:
- # Initialise longest_length to 0
- longest_length = 0
- # Initialise window starting at index 0 with left_bound and right_bound
- left_bound = 0
- right_bound = 0
- # Initialise positions of 0s to empty deque zero_indexes
- zero_indexes = deque([])
- # Iteratively increase the right_bound
- while right_bound < len(A):
- # When we see a 0
- if A[right_bound] == 0:
- # Enqueue that 0's position in zero_indexes
- zero_indexes.append(right_bound)
- # If length of zero_indexes is > K:
- if len(zero_indexes) > K:
- # popleft from zero_indexes
- first_zero_in_prev_window = zero_indexes.popleft()
- # Move left bound to the first index (elem) in zero_indexes (after popping)
- left_bound = first_zero_in_prev_window + 1
- # Move right bound to avoid double-counting the same right bound
- right_bound += 1
- # Skip to next iteration of loop because longest_length can't have increased
- continue
- # Update longest_length
- curr_window_size = right_bound - left_bound + 1
- longest_length = max(longest_length, curr_window_size)
- # Increment right bound to continue traversal
- right_bound += 1
- # Return longest length detected
- return longest_length
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement