# 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& nums) { int ans = 0; int count0 = 0; for (int l = 0, r = 0; r < nums.size(); ++r) { if (nums[r] == 0) ++count0; while (count0 == 2) if (nums[l++] == 0) --count0; 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 count0 = 0; for (int l = 0, r = 0; r < nums.length; ++r) { if (nums[r] == 0) ++count0; while (count0 == 2) if (nums[l++] == 0) --count0; 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 count0 = 0 l = 0 for r, num in enumerate(nums): if num == 0: count0 += 1 while count0 == 2: if nums[l] == 0: count0 -= 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& nums) { int l = 0; int count0 = 0; for (const int num : nums) { if (num == 0) ++count0; if (count0 > 1 && nums[l++] == 0) --count0; } 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 count0 = 0; for (final int num : nums) { if (num == 0) ++count0; if (count0 > 1 && nums[l++] == 0) --count0; } 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 count0 = 0 for num in nums: if num == 0: count0 += 1 if count0 > 1: if nums[l] == 0: count0 -= 1 l += 1 return len(nums) - l - 1