Longest Subarray of 1's After Deleting One Element
The key idea
You must delete exactly one element, so the answer is the longest window that contains at most ONE zero, minus one for the deleted slot. Slide a window that allows a single zero; when a second zero enters, shrink from the left until only one zero remains.
Problem
Given a binary array nums, you should delete one element from it.
Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.
Constraints
- 1 <= nums.length <= 10^5
- nums[i] is either 0 or 1.
Examples
Input: nums = [1,1,0,1]
Output: 3
Input: nums = [0,1,1,1,0,1,1,0,1]
Output: 5
Input: nums = [1,1,1]
Output: 2
Complexity
Time: O(n) Space: O(1)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Sliding Window problems
- Find All Anagrams in a StringMEDIUM
- Longest Continuous Increasing SubsequenceEASY
- Longest Repeating Character ReplacementMEDIUM
- Longest Substring Without Repeating CharactersMEDIUM
- Max Consecutive Ones IIIMEDIUM
- Maximum Average Subarray IEASY
- Maximum Number of Vowels in a Substring of Given LengthMEDIUM
- Minimum Size Subarray SumMEDIUM
- Minimum Window SubstringHARD
- Permutation in StringMEDIUM
- Sliding Window MaximumHARD
- Substring with Concatenation of All WordsHARD