Solving tips
- Reframe 'delete one element' as a sliding window containing at most one zero - that single zero is the deleted slot.
- Grow the right edge; when zeros exceed 1, advance left past the first zero. The kept ones = window size minus one.
- Return right - left (window length minus the mandatory deletion), so an all-ones array of length k correctly yields k-1.
- Target O(n) time, O(1) space; a prefix/suffix ones-count DP is an equally valid O(n) framing.
Problem
Given a binary array nums, you must delete exactly one element. After the deletion, return the length of the longest contiguous run of 1s in the resulting array. If every possible result is empty (i.e. the array was all zeros, or a single element), return 0.
Note the “exactly one deletion” rule: even an all-1s array must give one element up.
Examples
nums = [1,1,0,1]→3— delete the0at index 2 to get[1,1,1].nums = [0,1,1,1,0,1,1,0,1]→5— delete the0at index 4, joining the two runs into1,1,1,1,1.nums = [1,1,1]→2— no zeros, but you must still delete one1, leaving[1,1].
Constraints
1 <= nums.length <= 10⁵nums[i]is0or1.
Think about it first
Hint 1
Deleting one element and joining its neighbors is the same as choosing a window that contains at most one zero — that single zero is the element you delete. The kept count is then the number of ones in that window.Hint 2
DP view: for each index computeleft[i] = consecutive ones ending just before i, and right[i] = consecutive ones starting just after i. Treating position i as the deleted slot, you can bridge left[i] + right[i] ones.
Hint 3
Or slide a window[l, r] rightward, counting zeros inside; when the count exceeds 1, advance l. The answer is the largest (window size − 1), since exactly one element is always removed.