Advertisement
sak1b

https://leetcode.com/problems/count-number-of-nice-subarrays

Dec 19th, 2020
739
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int numberOfSubarrays(vector<int>& nums, int k) {
  4.         int n=nums.size();
  5.         vector<int> pos;
  6.         int res=0;
  7.         int count=0;
  8.         for(int i=0;i<n;i++)
  9.         {
  10.             if(nums[i]%2!=0)
  11.             {  
  12.                 pos.push_back(i);
  13.             }
  14.         }
  15.         // for(auto x:pos)
  16.         // {
  17.         //     cout<<x<<", ";
  18.         // }cout<<endl;
  19.         int i=0;
  20.         int j=k-1;
  21.         int left=0;
  22.         int right=0;
  23.         int m=pos.size();
  24.         while(i<m && j<m)
  25.         {
  26.            
  27.                
  28.            // cout<<pos[i]<<" "<<pos[j]<<endl;
  29.             if(i==0 && pos[i]==0)
  30.                 left=1;
  31.             else if( i==0 && pos[i]!=0)
  32.                 left= pos[i]+1;
  33.             else
  34.                 left=pos[i]-pos[i-1];
  35.            
  36.             if(j==m-1 && pos[j]==n-1)
  37.                 right=1;
  38.             else if(j==m-1 && pos[j]!=n-1)
  39.                 right=(n-1)-pos[j]+1;
  40.             else
  41.                 right=pos[j+1]-pos[j];
  42.            
  43.             res+=(left*right);
  44.             i++;
  45.             j++;
  46.         }
  47.        
  48.        
  49.        // cout<<"--"<<endl;
  50.         return res;
  51.     }
  52. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement