Pretty straightforward!
We use sliding window and when the 0 appears in that window more than once, we would break the window, otherwise we would keep update the answer.
class Solution {
public:
int longestSubarray(vector<int>& nums) {
int n = nums.size();
int l = 0;
int temp = 0;
int ans = 0;
// if temp > 1, break the window, otherwise accumulate the ans
for(int r = 0; r < n; r++){
while(temp > 1 && l <= r){
if(nums[l] == 0){
l++;
temp--;
break;
}
l++;
}
if(nums[r] == 0){
temp++;
}
if(temp == 0 || temp == 1){
ans = max(ans, r - l);
}
}
return ans;
}
};