Longest Subarray of 1's After Deleting One Element - Problem
Given a binary array nums containing only 0s and 1s, you must delete exactly one element from it.
Your task is to return the maximum length of the longest contiguous subarray containing only 1s after deleting one element. If no such subarray exists, return 0.
Key Points:
- You must delete exactly one element (cannot skip deletion)
- The resulting subarray must contain only 1s
- Return the length of the longest such subarray
Example: In array [1,1,0,1], if we delete the 0 at index 2, we get [1,1,1] with length 3.
Input & Output
example_1.py โ Basic case
$
Input:
[1,1,0,1]
โบ
Output:
3
๐ก Note:
After deleting the 0 at index 2, we get [1,1,1] which has length 3.
example_2.py โ Multiple zeros
$
Input:
[0,1,1,1,0,1,1,0,1]
โบ
Output:
5
๐ก Note:
We can delete one of the zeros to connect sequences. Deleting the 0 at index 4 gives us a subarray [1,1,1,1,1] of length 5.
example_3.py โ All ones
$
Input:
[1,1,1,1]
โบ
Output:
3
๐ก Note:
Since we must delete exactly one element, we delete any 1 and get length 3.
Constraints
- 1 โค nums.length โค 105
- nums[i] is either 0 or 1
- You must delete exactly one element
Visualization
Tap to expand
Understanding the Visualization
1
Start measurement
Place the measuring tape at the beginning of the necklace
2
Expand the tape
Stretch the tape to include more pearls, counting any black beads
3
Adjust when needed
If the tape spans more than one black bead, shrink it from the left
4
Record maximum
Track the longest stretch that spans at most one black bead
Key Takeaway
๐ฏ Key Insight: By maintaining a sliding window with at most one zero, we efficiently find the longest possible subarray of 1s after mandatory deletion - the window size minus one gives us our answer!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code