Longest Subarray of 1's After Deleting One Element Problem
Description
LeetCode Problem 1493.
You are 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.
Example 1:
Input: nums = [1,1,0,1]
Output: 3
Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.
Example 2:
Input: nums = [0,1,1,1,0,1,1,0,1]
Output: 5
Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].
Example 3:
Input: nums = [1,1,1]
Output: 2
Explanation: You must delete one element.
Constraints:
1 <= nums.length <= 10^5nums[i]is either 0 or 1.
Solution
Approach: Sliding Window With at Most One Zero
After deleting one element, a run of 1's in the result comes from a stretch of the original array that holds at most one 0: delete that 0 and the rest are all 1's. So the task is the same as finding the longest window nums[j..i] with at most one zero, and the answer is its length minus one, i - j.
Grow the window by moving i to the right and count the zeros inside it. Whenever the count goes above one, move j to the right until a zero has left the window. After each step, i - j is a candidate answer.
The tricky case is an array with no zeros at all, like [1,1,1]: we still have to delete one element, so the answer is n - 1, not n. Subtracting one from every window length handles this for free. An array of only zeros gives 0.
Complexity: O(n) time, since each pointer only moves forward, and O(1) extra space.
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
ans = 0
zeros = 0 # zeros inside the window nums[j..i]
j = 0
for i, x in enumerate(nums):
zeros += x ^ 1
while zeros > 1:
zeros -= nums[j] ^ 1
j += 1
ans = max(ans, i - j) # window length minus the one deleted element
return ans