LeetCode 29th bi-weekly contest 5434. The longest subarray with all 1s after deleting one element

Topic link
Insert picture description hereInsert picture description here

  • You can do it with a sliding window, but simulation is also possible
class Solution {
    
    
public:
    int longestSubarray(vector<int>& nums) {
    
    

        int ans=0;
        int pos=1;
        int y=0;
        int temp=0;
        int flag=0;
        int z=1;
        for(int i=0;i<nums.size();i++)
        {
    
    
            if(nums[i]==1)
            {
    
    
                temp++;
                ans=max(temp,ans);
                pos=1;
            }
           if(nums[i]==0)
           {
    
    
               if(pos==1)
               {
    
    
                   if(flag==0)
                   {
    
    
                       y=temp;
                       flag=1;
                   
                   }
                   else
                   {
    
    
                        pos=0;
                        temp-=y;
                        y=temp;
                   continue;
                   }
               }
               else
               {
    
    
                   temp=0;
                   flag=0;
                   y=0;
               }
               
           }
          z&=nums[i];
        }
        if(z==1)
            return nums.size()-1;
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/qq_43663263/article/details/106998255