LC1004. Max Consecutive Ones III¶
Problem Description¶
LeetCode Problem 1004: Given a binary array nums
and an integer k
, return the maximum number of consecutive 1
's in the array if you can flip at most k
0
's.
Note integer type can be rest to 0
Similar Questions:¶
Clarification¶
- Binary tree of integer type?
Assumption¶
- Integer type can cover subarray left and right indices
Solution¶
Approach - Slide Window¶
Use a sliding window (left and right pointers) to find the longest sequence with at most k zeros:
- Expand the window by moving the right pointer forward until reaching invalid window, more than k
zeros in the current window
- Shrink the window by moving the left pointer forward until having a valid window, one of fewer 0's in the current window
class Solution {
public:
int longestOnes(vector<int>& nums, int k) {
int nOneKZero = 0;
int length = 0;
int nZeroInWindow = 0;
int left = 0;
for (int right = 0; right < nums.size(); right++) {
// When expanding to right, update number of zeros in the window
if (nums[right] == 0) {
nZeroInWindow++;
}
// If window is invalid, shrink from left
while (nZeroInWindow > k) {
if (nums[left] == 0) {
nZeroInWindow--;
}
left++;
}
// Update length
length = right - left + 1;
nOneKZero = max(nOneKZero, length);
}
return nOneKZero;
}
};
Complexity Analysis¶
- Time complexity: \(O(n)\)
In the worst case, both left and right pointers iterate through the element (total twice). It is still \(O(n)\) time complexity. - Space complexity: \(O(1)\)
Only use several local variables.