SDE & MLE Prep

1493. Longest Subarray of 1's After Deleting One Element

Problem

Delete exactly one element from the binary array nums, then return the length of the longest non-empty subarray of only 1s (0 if there is none).

Example: [0,1,1,1,0,1,1,0,1] → 5; [1,1,1] → 2 (you must delete one)

Longest window containing at most one zero; the deleted element is inside it, so the answer is window length − 1 (which also handles the all-ones case, where a 1 must be deleted).

Complexity: O(n).

class Solution:
    def longestSubarray(self, nums: List[int]) -> int:
        lo = zeros = best = 0
        for hi, x in enumerate(nums):
            zeros += x == 0
            while zeros > 1:
                zeros -= nums[lo] == 0
                lo += 1
            best = max(best, hi - lo)          # (hi - lo + 1) - 1 deleted element
        return best