Count all subsequences having product less than K in C++



In this tutorial, we will be discussing a program to find the number of sub sequences having product less than K.

For this we will be provided with non-negative array and a value k. Our task is to find all the subsequences in the array having product less than k.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//counting subsequences with product
//less than k
int count_sub(vector<int> &arr, int k){
   int n = arr.size();
   int dp[k + 1][n + 1];
   memset(dp, 0, sizeof(dp));
   for (int i = 1; i <= k; i++) {
      for (int j = 1; j <= n; j++) {
         dp[i][j] = dp[i][j - 1];
         if (arr[j - 1] <= i && arr[j - 1] > 0)
            dp[i][j] += dp[i/arr[j-1]][j-1] + 1;
      }
   }
   return dp[k][n];
}
int main(){
   vector<int> A;
   A.push_back(1);
   A.push_back(2);
   A.push_back(3);
   A.push_back(4);
   int k = 10;
   cout << count_sub(A, k) << endl;
}

Output

11

Advertisements