Subarray Product Less Than K in C++

C++Server Side ProgrammingProgramming

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 −

 Live Demo

#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
raja
Published on 27-Feb-2020 10:59:32
Advertisements