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.
1class Solution {
2 public int longestOnes(int[] nums, int k) {
3 int left = 0, maxLen = 0, zerosCount = 0;
4 for (int right = 0; right < nums.length; right++) {
5 if (nums[right] == 0) {
6 zerosCount++;
7 }
8 while (zerosCount > k) {
9 if (nums[left] == 0) {
10 zerosCount--;
11 }
12 left++;
13 }
14 maxLen = Math.max(maxLen, right - left + 1);
15 }
16 return maxLen;
17 }
18}
This Java solution is functionally similar to the other language solutions. It makes use of indices to track window bounds and maintain the zero count within the window.