Sponsored
Sponsored
This approach involves using a sliding window distinguished by two pointers. The window expands by moving the right pointer and checks whether the number of zeros within the window exceeds the allowed count 'k'. If it does, we move the left pointer to shrink the window until the condition is satisfied. We aim to find the maximum window size that can be achieved following this condition.
Time Complexity: O(n), where n is the length of the input array. Each element is processed at most twice.
Space Complexity: O(1), as no additional space is used aside from variables.
1def longest_ones(nums, k):
2 left = 0
3 max_len = 0
4 zeros_count = 0
5
6 for right in range(len(nums)):
7 if nums[right] == 0:
8 zeros_count += 1
9
10 while zeros_count > k:
11 if nums[left] == 0:
12 zeros_count -= 1
13 left += 1
14
15 max_len = max(max_len, right - left + 1)
16
17 return max_len
This Python solution initializes two pointers 'left' and 'right' with 'left' starting from 0. As 'right' iterates over the array, it checks and counts zeros. If the count of zeros exceeds k, the 'left' pointer moves forward to reduce zeros count, effectively shrinking the window.