Skip to main content
Back to problems
Leetcode
Medium
Arrays
Sliding Window
Two Pointers
Amazon
Longest Subarray of 1s After Deleting One Element

Find the maximum length of a contiguous subarray of 1s you can obtain after deleting exactly one element from a binary array.

Acceptance 0%
Problem Statement

Given a binary array nums, delete exactly one element from the array and then consider the longest contiguous segment consisting only of 1s in the remaining elements.

Return the length of the longest such segment you can achieve.

Because one element must be deleted, the answer may be 0 if the array has no 1s.

Input Format

  • An integer array nums containing only 0s and 1s.
  • Exactly one element must be removed from the array.

Output Format

  • Return a single integer: the maximum length of a contiguous subarray of 1s after deleting one element.

Constraints

  • 1 <= nums.length
  • nums[i] is either 0 or 1
  • Delete exactly one element.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1,1,0,1]

Output

3

Explanation

Delete the zero at index 2. The remaining array is [1,1,1], whose longest contiguous run of 1s has length 3.

Example 2

Input

nums = [0,1,1,1,0,1,1,0,1]

Output

5

Explanation

Delete the zero at index 4 to connect the first three 1s with the next two 1s, forming a run of length 5.

Show 1 more example

Example 3

Input

nums = [1,1,1]

Output

2

Explanation

You must delete one element, so the longest run of 1s becomes 2.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.