medium Max Consecutive Ones III
Problem Statement
Given an array nums containing 1 and 0 digits, return the maximum number of consecutive 1s if you can flip at most any k 0s.
Examples
-
Example 1:
- Input: nums =
[1, 0, 1, 1, 0, 0, 1, 1, 1, 0], k =2 - Expected Output:
7 - Justification: Flipping the two 0s in the middle section
[0, 0]results in the longest continuous sequence of 1s:[1, 1, 1, 1, 1, 1, 1].
- Input: nums =
-
Example 2:
- Input: nums =
[0, 1, 1, 0, 1, 0, 1, 0, 1], k =1 - Expected Output:
4 - Justification: Flipping the
0at index 3 will yield a maximum continuous sequence of four 1s.
- Input: nums =
-
Example 3:
- Input: nums =
[1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1], k =3 - Expected Output:
8 - Justification: Flipping the three 0s in the middle
[0, 0, 0]results in the longest sequence of 1s:[1, 1, 1, 1, 1, 1, 1, 1].
- Input: nums =
Constraints:
- 1 <= nums.length <= 105
- nums[i] is either 0 or 1.
- 0 <= k <= nums.length
Try it yourself
Try solving this question here:
✅ Solution Max Consecutive Ones III
Problem Statement
Given an array nums containing 1 and 0 digits, return the maximum number of consecutive 1s if you can flip at most any k 0s.
Examples
-
Example 1:
- Input: nums =
[1, 0, 1, 1, 0, 0, 1, 1, 1, 0], k =2 - Expected Output:
7 - Justification: Flipping the two 0s in the middle section
[0, 0]results in the longest continuous sequence of 1s:[1, 1, 1, 1, 1, 1, 1].
- Input: nums =
-
Example 2:
- Input: nums =
[0, 1, 1, 0, 1, 0, 1, 0, 1], k =1 - Expected Output:
4 - Justification: Flipping the
0at index 3 will yield a maximum continuous sequence of four 1s.
- Input: nums =
-
Example 3:
- Input: nums =
[1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1], k =3 - **Expected Output:
8 - Justification: Flipping the three 0s in the middle
[0, 0, 0]results in the longest sequence of 1s:[1, 1, 1, 1, 1, 1, 1, 1].
- Input: nums =
Constraints:
- 1 <= nums.length <= 105
- nums[i] is either 0 or 1.
- 0 <= k <= nums.length
Solution
To solve this problem, we can use a sliding window approach. This technique involves expanding and contracting a window within the array to encapsulate sequences that fit our criteria. By moving this window throughout the array, we can identify the longest sequence of 1s that can be obtained by flipping at most a given number of 0s. The reason this method is effective is that it allows us to efficiently examine each potential sequence without redundant calculations. This approach is not only intuitive but also optimizes the process by reducing unnecessary computations.
The key lies in maintaining the count of zeros within our current window. We expand the window by moving the right pointer forward if the number of zeros within it is less than or equal to the allowed limit. If the number of zeros exceeds the limit, we contract the window by moving the left pointer forward. Throughout this process, we keep track of the maximum window size, which ultimately gives us the longest sequence of 1s achievable.
Step-by-step Algorithm
- Initialize two pointers,
leftandright, both set to 0, and a variablemaxLenfor tracking the maximum length of 1s sequence. - Initialize a variable
zeroCountto keep track of the number of zeros in the current window. - Iterate through the array using the
rightpointer.- If the element at the
rightpointer is 0, incrementzeroCount. - While
zeroCountis greater than the allowed number of flips, move theleftpointer forward, decrementingzeroCountif a 0 is left behind. - Update
maxLenwith the maximum of its current value and the size of the current window (right - left + 1).
- If the element at the
- Return
maxLenas the result.
Algorithm Walkthrough
-
Initial State:
left = 0,right = 0,zeroCount = 0,maxLen = 0.
-
First step:
A[0] = 1, no change inzeroCount.right = 0,maxLen = 1(current window:[1]).
-
Move Right to 1:
A[1] = 1, no change inzeroCount.right = 1,maxLen = 2(current window:[1, 1]).
-
Move Right to 2:
A[2] = 0,zeroCount = 1 <= k (3).right = 2,maxLen = 3(current window:[1, 1, 0]).
-
Move Right to 3:
A[3] = 0,zeroCount = 2 <= k (3).right = 3,maxLen = 4(current window:[1, 1, 0, 0]).
-
Move Right to 4:
A[4] = 0,zeroCount = 3 <= k (3).right = 4,maxLen = 5(current window:[1, 1, 0, 0, 0]).
-
Move Right to 5:
A[5] = 1,zeroCount = 3 <= k (3).right = 5,maxLen = 6(current window:[1, 1, 0, 0, 0, 1]).
-
Move Right to 6:
A[6] = 1,zeroCount = 3 <= k (3).right = 6,maxLen = 7(current window:[1, 1, 0, 0, 0, 1, 1]).
-
Move Right to 7:
A[7] = 1,zeroCount = 3 <= k (3).right = 7,maxLen = 8(current window:[1, 1, 0, 0, 0, 1, 1, 1]).
-
Move Right to 8 and Adjust Left:
A[8] = 0,zeroCount = 4>K.- Shift
leftto 1 (A[1] = 1, no change inzeroCount). right = 8,maxLen = 8(current window:[1, 0, 0, 0, 1, 1, 1, 0]).
-
Continue Moving Right and Adjusting Left:
- Continue this process, moving
rightforward and adjustingleftwhenzeroCountexceedsK. - Update
maxLeneach time.
- Continue this process, moving
-
Final Output:
- The loop ends when
rightreaches the end of the array. - Final
maxLenis determined (expected to be8for this example).
- The loop ends when
Code
public class Solution {
public int longestOnes(int[] A, int K) {
int left = 0, maxLen = 0, zeroCount = 0;
// Iterate through the array with right pointer
for (int right = 0; right < A.length; right++) {
// Increment zeroCount if current element is 0
if (A[right] == 0) zeroCount++;
// Move left pointer to reduce zeroCount within limit
while (zeroCount > K) {
if (A[left] == 0) zeroCount--;
left++;
}
// Update maxLen for the longest window found
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
}
// Main method for testing
public static void main(String[] args) {
Solution solution = new Solution();
// Example 1
int[] example1 = { 1, 0, 1, 1, 0, 0, 1, 1, 1, 0 };
System.out.println("Example 1: " + solution.longestOnes(example1, 2)); // Expected output: 7
// Example 2
int[] example2 = { 0, 1, 1, 0, 1, 0, 1, 0, 1 };
System.out.println("Example 2: " + solution.longestOnes(example2, 1)); // Expected output: 4
// Example 3
int[] example3 = { 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1 };
System.out.println("Example 3: " + solution.longestOnes(example3, 3)); // Expected output: 8
}
}
Complexity Analysis
Time Complexity:
- The algorithm iterates through the array once with the
rightpointer, whereNis the length of the array. - The
leftpointer moves only in one direction and can move at mostNtimes throughout the entire array. - Since both pointers traverse the array at most once, the overall time complexity is linear,
O(N).
Space Complexity:
- The space used by the algorithm is independent of the size of the input array.
- Only a fixed number of variables (
left,right,maxLen,zeroCount) are used, which occupy constant space. - Thus, the space complexity is constant,
.
🤖 Don't fully get this? Learn it with Claude
Stuck on Max Consecutive Ones III? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Max Consecutive Ones III** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Max Consecutive Ones III** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Max Consecutive Ones III**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Max Consecutive Ones III**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.