<p>Given a binary array <code>nums</code>, you should delete one element from it.</p>

<p>Return <em>the size of the longest non-empty subarray containing only </em><code>1</code><em>&#39;s in the resulting array</em>. Return <code>0</code> if there is no such subarray.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,1,0,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1&#39;s.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [0,1,1,1,0,1,1,0,1]
<strong>Output:</strong> 5
<strong>Explanation:</strong> After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1&#39;s is [1,1,1,1,1].
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,1,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> You must delete one element.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>

class Solution {
public:
    int longestSubarray(vector<int>& nums) {
        int zer = 0;
        int n= nums.size();
        for(int i=0;i<n;i++){
            if(nums[i]==0) zer += 1;
        }
        if(zer == n) return 0;
        if(zer==0) return n-1;
        if(n == 1 && zer == 1) return 0;

        int l=0;
        for(int i=0;i<n;i++){
            if(nums[i] == 1){
                l = i;
                break;
            }
        }
        int r = l;
        int a = l,b= r;
        map<int,int>mp;
        while(l<=r && r<n){
            if(nums[r] == 0){
                l = r;
                r += 1;
            }
            else if(nums[l]==0){
                l += 1;
                r = l;
            }
            else if(nums[l] == 1 && nums[r]==1 && (r-l+1>b-a+1)){
                b = r;
                a = l;
                
                
            }
            if(nums[l] == 1 && nums[r]==1){
                mp[l] = r;
                r += 1;
                
            }
            
        }
        int an = b-a+1;
        vector<vector<int>>ans;
        for(auto &it:mp){
            ans.push_back({it.first,it.second});
        }
        for(int i=1;i<ans.size();i++){
            if(ans[i][0] == ans[i-1][1]+2){
                an = max(an,ans[i][1]-ans[i][0]+1 + ans[i-1][1]-ans[i-1][0]+1);
            }
        }
        return an;
    }
};
59600