Longest Subarray of 1's After Deleting One Element
Master this topic with zero to advance depth.
Longest Subarray of 1's After Deleting One Element
Given a binary array nums, you must delete exactly one element. Return the maximum number of consecutive 1's remaining.
Visual Representation
nums = [1, 1, 0, 1]
[1, 1, 0, 1]
^ Delete this 0
Remaining: [1, 1, 1] -> Len 3
Sliding Window Rule:
Window must contain at most ONE zero.
Final Result = WindowSize - 1Examples
Level I: Brute Force
Intuition
Iterate through every element in the array. For each element, assume it is the one being deleted, and then find the longest contiguous block of 1's that can be formed using the remaining elements.
Thought Process
- Iterate through each index
ifrom0ton-1. - Simulate deleting
nums[i]. - After 'deletion', find the longest sequence of 1's in the remaining array.
- Track the maximum length found across all possible deletions.
Detailed Dry Run
| Deleting Index | Resulting Array | Max 1s | Result |
|---|---|---|---|
| 0 | [1, 0, 1] | 1 | 1 |
| 1 | [1, 0, 1] | 1 | 1 |
| 2 | [1, 1, 1] | 3 | 3 |
| 3 | [1, 1, 0] | 2 | 3 |
Level III: Optimal (Sliding Window)
Intuition
Thought Process
This is equivalent to 'Max Consecutive Ones III' with k = 1. We find the longest window with at most one zero. Since we must delete one element, the result is always WindowSize - 1.
Patterns
- Variable Window: Expand as long as zeros .
- Constraint: If
zeros > 1, shrink from left.
Detailed Dry Run
| R | Num | Zeros | Window Size | Result |
|---|---|---|---|---|
| 0 | 1 | 0 | 1 | 0 |
| 1 | 1 | 0 | 2 | 1 |
| 2 | 0 | 1 | 3 | 2 |
| 3 | 1 | 1 | 4 | 3 (MAX) |
⚠️ Common Pitfalls & Tips
If the array consists only of 1's, the result should be N - 1, not N. Don't forget that one deletion is MANDATORY.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.