InterviewPrepKit

Home / Coding / Algorithm & Data Structure / 1-D Dynamic Programming

Longest Subarray of 1's After Deleting One Element

medium Original ↗ 00:00

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 no such run exists (for example, an all-zero array or a single element), return 0.

Deletion is mandatory, so even an all-1s array must give up one element.

Examples

  • nums = [1,1,0,1]3 — delete the 0 at index 2 to get [1,1,1].
  • nums = [0,1,1,1,0,1,1,0,1]5 — delete the 0 at index 4, joining the two runs into 1,1,1,1,1.
  • nums = [1,1,1]2 — no zeros, but you must still delete one 1, leaving [1,1].

Constraints

  • 1 <= nums.length <= 10⁵
  • nums[i] is 0 or 1.

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 compute left[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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug