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.
1function longestOnes(nums, k) {
2 let left = 0;
3 let maxLen = 0;
4 let zerosCount = 0;
5
6 for (let right = 0; right < nums.length; right++) {
7 if (nums[right] === 0) {
8 zerosCount++;
9 }
10
11 while (zerosCount > k) {
12 if (nums[left] === 0) {
13 zerosCount--;
14 }
15 left++;
16 }
17
18 maxLen = Math.max(maxLen, right - left + 1);
19 }
20
21 return maxLen;
22}
The JavaScript solution uses a for loop to iterate over the 'nums' array, maintaining a count of zeros within the current window. If the count of zeros exceeds k, the window is shrunk by incrementing the 'left' pointer.