 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Subarray Product Less Than K in C++
Suppose we have given an array of positive integers nums. We have to count and print the number of (contiguous) subarrays where the product of each the elements in the subarray is less than k. So if the input is like [10,5,2,6] and k := 100, then the output will be 8. So the subarrays will be [[10], [5], [2], [6], [10, 5], [5, 2], [2, 6] and [5, 2, 6]]
To solve this, we will follow these steps −
- temp := 1, j := 0 and ans := 0
- for i in range 0 to size of the array- temp := temp * nums[i]
- while temp >= k and j <= i, do- temp := temp / nums[j]
- increase j by 1
 
- ans := ans + (i – j + 1)
 
- return ans
Example(C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; typedef long long int lli; class Solution { public:    int numSubarrayProductLessThanK(vector<int>& nums, int k) {       lli temp = 1;       int j = 0;       int ans = 0;       for(int i = 0; i < nums.size(); i++){          temp *= nums[i];          while(temp >= k && j <= i) {             temp /= nums[j];             j++;          }          ans += (i - j + 1);       }       return ans;    } }; main(){    Solution ob;    vector<int> v = {10,5,2,6};    cout << (ob.numSubarrayProductLessThanK(v, 100)); }  Input
[10,5,2,6] 100
Output
8
Advertisements
 