Skip to main content
Back to problems
#1493
Medium Algorithms

Longest subarray of 1s after deleting one element

Array Dynamic Programming Sliding Window
71.1% acceptance
Feb 25, 2026
4791
110
Given a binary array nums, you should delete one element from it. Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn longest_subarray(nums: Vec<i32>) -> i32 {
    let (mut l, mut zeros, mut best) = (0usize, 0i32, 0i32);
    for r in 0..nums.len() {
      if nums[r] == 0 { zeros += 1; }
      while zeros > 1 {
        if nums[l] == 0 { zeros -= 1; }
        l += 1;
      }
      // window length is (r - l), must delete one element
      best = best.max((r - l) as i32);
    }
    best
  }
}