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.
1public class 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 C# implementation employs the same sliding window mechanism, incrementing and decrementing pointers to maintain the largest feasible subarray of ones, adjusting for zero occurrences.