Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
Before deleting one element, a usable window contains at most one zero. Its length minus one is the number of ones that can remain: remove its zero if present, or remove a one when the window is already all ones. The deletion is mandatory.
Approach
Maintain a left boundary and a flag indicating whether the window contains a zero. When a second zero arrives, advance the left boundary past the previous zero, then retain the new zero in the window. After each right-end update, maximize right - left, which is the window length minus one. Return the best value; an all-ones array yields n - 1, not n.
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
n = len(nums)
z = False
l = res = 0
for r in range(n):
if nums[r] == 0:
while z:
if nums[l] == 0:
z = False
l += 1
z = True
res = max(res, r - l) # take maximum window - 1 | Always remove exactly 1 element
return resComplexity analysis
Each element enters and leaves the at-most-one-zero window once. Time is O(n) and auxiliary space is O(1).
