28. Maximize Number of 1's
β GFG solution to the Maximize Number of 1's problem: find maximum consecutive 1's by flipping at most k zeros using optimized sliding window technique. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given a binary array arr[]
containing only 0s and 1s and an integer k
. You are allowed to flip at most k 0s to 1s. Your task is to find the maximum number of consecutive 1's that can be obtained in the array after performing the operation at most k times.
A flip operation changes a 0 to 1. The goal is to maximize the length of the longest contiguous subarray of 1's after optimally choosing which zeros to flip.
π Examples
Example 1
Input: arr[] = [1, 0, 1], k = 1
Output: 3
Explanation: By flipping the zero at index 1, we get the longest subarray from index 0 to 2 containing all 1's.
Example 2
Input: arr[] = [1, 0, 0, 1, 0, 1, 0, 1], k = 2
Output: 5
Explanation: By flipping the zeroes at indices 4 and 6, we get the longest subarray from index 3 to 7 containing all 1's.
Example 3
Input: arr[] = [1, 1], k = 2
Output: 2
Explanation: Since the array is already having the max consecutive 1's, hence we don't need to perform any operation. Hence the answer is 2.
π Constraints
$1 \le \text{arr.size()} \le 10^5$
$0 \le k \le \text{arr.size()}$
$0 \le \text{arr}[i] \le 1$
β
My Approach
The optimal approach uses the Sliding Window technique to efficiently find the maximum window that contains at most k
zeros:
Optimized Sliding Window
Initialize Variables:
Use two pointers:
l
(left/start) andr
(right/end) for the sliding window.Maintain
zeros
counter to track zeros in current window.Track
maxLen
to store the maximum window length found.
Expand Window:
Move
r
pointer and incrementzeros
ifarr[r]
is 0.This represents including more elements in our potential flip window.
Contract Window:
If
zeros > k
(exceeded flip limit), shrink window from left.Move
l
pointer and decrementzeros
ifarr[l]
was 0.Continue until
zeros <= k
(valid window restored).
Update Result:
After each valid window expansion, update
maxLen
with current window size(r - l + 1)
.
Continue Until End:
Repeat until
r
pointer covers the entire array.
Key Insight: Instead of actually flipping zeros, we find the longest subarray containing at most k
zeros. This subarray represents the optimal segment where we can flip all zeros to get maximum consecutive 1's.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the size of the array. Each element is visited at most twice - once by the right pointer during expansion and once by the left pointer during contraction.
Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for variables (pointers and counters).
π§βπ» Code (C++)
class Solution {
public:
int maxOnes(vector<int>& arr, int k) {
int l = 0, zeros = 0, maxLen = 0;
for (int r = 0; r < arr.size(); r++) {
zeros += (arr[r] == 0);
while (zeros > k) zeros -= (arr[l++] == 0);
maxLen = max(maxLen, r - l + 1);
}
return maxLen;
}
};
β Code (Java)
class Solution {
public int maxOnes(int arr[], int k) {
int l = 0, zeros = 0, maxLen = 0;
for (int r = 0; r < arr.length; r++) {
if (arr[r] == 0) zeros++;
while (zeros > k) if (arr[l++] == 0) zeros--;
maxLen = Math.max(maxLen, r - l + 1);
}
return maxLen;
}
}
π Code (Python)
class Solution:
def maxOnes(self, arr, k):
l = zeros = maxLen = 0
for r in range(len(arr)):
zeros += (arr[r] == 0)
while zeros > k:
zeros -= (arr[l] == 0)
l += 1
maxLen = max(maxLen, r - l + 1)
return maxLen
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated