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.
1#include <stdio.h>
2
3int longestOnes(int* nums, int numsSize, int k) {
4 int left = 0, max_len = 0, zeros_count = 0;
5 for (int right = 0; right < numsSize; ++right) {
6 if (nums[right] == 0) {
7 zeros_count++;
8 }
9 while (zeros_count > k) {
10 if (nums[left] == 0) {
11 zeros_count--;
12 }
13 left++;
14 }
15 if (max_len < right - left + 1) {
16 max_len = right - left + 1;
17 }
18 }
19 return max_len;
20}
This C solution involves handling array index operations and uses standard integer manipulation to maintain the window for the longest segment of ones attained through permissible flipping of zeros.