Skip to content

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

Approach 1: Standard Sliding Window

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int longestSubarray(vector<int>& nums) {
    int ans = 0;
    int zeros = 0;

    for (int l = 0, r = 0; r < nums.size(); ++r) {
      if (nums[r] == 0)
        ++zeros;
      while (zeros == 2)
        if (nums[l++] == 0)
          --zeros;
      ans = max(ans, r - l);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int longestSubarray(int[] nums) {
    int ans = 0;
    int zeros = 0;

    for (int l = 0, r = 0; r < nums.length; ++r) {
      if (nums[r] == 0)
        ++zeros;
      while (zeros == 2)
        if (nums[l++] == 0)
          --zeros;
      ans = Math.max(ans, r - l);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def longestSubarray(self, nums: list[int]) -> int:
    ans = 0
    zeros = 0

    l = 0
    for r, num in enumerate(nums):
      if num == 0:
        zeros += 1
      while zeros == 2:
        if nums[l] == 0:
          zeros -= 1
        l += 1
      ans = max(ans, r - l)

    return ans

Approach 2: Non-shrinking Sliding Window

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int longestSubarray(vector<int>& nums) {
    int l = 0;
    int zeros = 0;

    for (const int num : nums) {
      if (num == 0)
        ++zeros;
      if (zeros > 1 && nums[l++] == 0)
        --zeros;
    }

    return nums.size() - l - 1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int longestSubarray(int[] nums) {
    int l = 0;
    int zeros = 0;

    for (final int num : nums) {
      if (num == 0)
        ++zeros;
      if (zeros > 1 && nums[l++] == 0)
        --zeros;
    }

    return nums.length - l - 1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def longestSubarray(self, nums: list[int]) -> int:
    l = 0
    zeros = 0

    for num in nums:
      if num == 0:
        zeros += 1
      if zeros > 1:
        if nums[l] == 0:
          zeros -= 1
        l += 1

    return len(nums) - l - 1