1.

Write a function to find number of subarrays with product less than K

Answer»


  • Input: arr = [1, 6, 2, 3, 2, 1], k = 12


  • Output: 11

int numSubarrayProductLessThanK(vector<int>& nums, int k) {
int ans=0;
int pdt=1;
int left=0,right=0;
while(right<=nums.size()-1){

pdt*=nums[right];
while(pdt>=k and left<nums.size()){
pdt/=nums[left];
left++;

}
if(right-left>=0)
ans+=right-left+1;//since on adding a new element new subarrays formed is r-i+1;
right++;

}
return ans;
}


  • Time Complexity: O(n)


  • Space Complexity: O(1)




Discussion

No Comment Found