table of Contents
Source of the subject: https://leetcode-cn.com/problems/longest-subarray-of-1s-after-deleting-one-element/
Title description
Give you a binary array nums, and you need to delete an element from it.
Please return the length of the longest non-empty sub-array containing only 1 in the result array of deleted elements.
If there is no such sub-array, please return 0.
提示 1:
输入:nums = [1,1,0,1]
输出:3
解释:删掉位置 2 的数后,[1,1,1] 包含 3 个 1 。
示例 2:
输入:nums = [0,1,1,1,0,1,1,0,1]
输出:5
解释:删掉位置 4 的数字后,[0,1,1,1,1,1,0,1] 的最长全 1 子数组为 [1,1,1,1,1] 。
示例 3:
输入:nums = [1,1,1]
输出:2
解释:你必须要删除一个元素。
示例 4:
输入:nums = [1,1,0,0,1,1,1,0,1]
输出:4
示例 5:
输入:nums = [0,0,0]
输出:0
General idea
- Given an array, you can delete a 0 in the interval, find the length of the longest remaining non-empty sub-array that only contains 1s, slide the sliding window once, and finally add a special treatment of all 1s in the string
Sliding window + dual pointer
class Solution {
public:
int longestSubarray(vector<int>& nums) {
int len = nums.size();
int left = 0, ans = 0, right = 0, zeros = 0;
for(; right < len ; ++right){
if(nums[right] == 0) ++zeros;
while(zeros >= 2){
if(nums[left] == 0) --zeros;
++left;
}
ans = max(ans, right - left + 1 - 1);
}
if(zeros == 0) ans = max(ans, right - left - 1);
return ans;
}
};
Complexity analysis
- Time complexity: O(n). n is the length of the array, both left and right can be regarded as sliding n times
- Space complexity: O(1)