The Wayback Machine - https://web.archive.org/web/20241003021021/https://www.geeksforgeeks.org/count-subsequences-product-less-k/
Open In App

Count all subsequences having product less than K

Last Updated : 26 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a positive array, find the number of subsequences having a product smaller than or equal to K.
Examples: 

Input : [1, 2, 3, 4] 
        k = 10
Output :11 
Explanation: The subsequences are {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {1, 2, 3}, {1, 2, 4}

Input  : [4, 8, 7, 2] 
         k = 50
Output : 9


This problem can be solved using dynamic programming where dp[i][j] = number of subsequences having product less than i using the first j terms of the array, which can be obtained by: the number of subsequences using the first j-1 terms + the number of subsequences that can be formed using j-th term. 

Below is the implementation of the above approach:

C++
// CPP program to find number of subarrays having
// product less than k.
#include <bits/stdc++.h>
using namespace std;

// Function to count numbers of such subsequences
// having product less than k.
int productSubSeqCount(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++) {
   
            // number of subsequence using j-1 terms
            dp[i][j] = dp[i][j - 1];
  
            // if arr[j-1] > i it will surely make product greater
            // thus it won't contribute then
            if (arr[j - 1] <= i)

                // number of subsequence using 1 to j-1 terms
                // and j-th term
                dp[i][j] += dp[i/arr[j-1]][j-1] + 1;
        }
    }
    return dp[k][n];
}

// Driver code
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 << productSubSeqCount(A, k) << endl;
}
Java
// Java program to find number of subarrays 
// having product less than k.
import java.util.*;
class CountSubsequences
{
    // Function to count numbers of such 
    // subsequences having product less than k.
    public static int productSubSeqCount(ArrayList<Integer> arr,
                                                 int k)
    {
        int n = arr.size();
        int dp[][]=new int[k + 1][n + 1];
        
        for (int i = 1; i <= k; i++) {
            for (int j = 1; j <= n; j++) {
        
                // number of subsequence using j-1 terms
                dp[i][j] = dp[i][j - 1];
        
                // if arr[j-1] > i it will surely make 
                // product greater thus it won't contribute
                // then
                if (arr.get(j-1) <= i && arr.get(j-1) > 0)
    
                    // number of subsequence using 1 to j-1
                    // terms and j-th term
                    dp[i][j] += dp[i/arr.get(j - 1)][j - 1] + 1;
            }
        }
        return dp[k][n];
    }
    
    // Driver code
    public static void main(String args[])
    {
        ArrayList<Integer> A = new ArrayList<Integer>();
        A.add(1);
        A.add(2);
        A.add(3);
        A.add(4);
        int k = 10;
        System.out.println(productSubSeqCount(A, k));
    }
}

// This Code is contributed by Danish Kaleem
C#
// C# program to find number of subarrays 
// having product less than k. 
using System ;
using System.Collections ;

class CountSubsequences 
{ 
    // Function to count numbers of such 
    // subsequences having product less than k. 
    public static int productSubSeqCount(ArrayList arr, int k) 
    { 
        int n = arr.Count ;
        int [,]dp = new int[k + 1,n + 1]; 
        
        for (int i = 1; i <= k; i++) { 
            for (int j = 1; j <= n; j++) { 
        
                // number of subsequence using j-1 terms 
                dp[i,j] = dp[i,j - 1]; 
        
                // if arr[j-1] > i it will surely make 
                // product greater thus it won't contribute 
                // then 
                if (Convert.ToInt32(arr[j-1]) <= i && Convert.ToInt32(arr[j-1]) > 0) 
    
                    // number of subsequence using 1 to j-1 
                    // terms and j-th term 
                    dp[i,j] += dp[ i/Convert.ToInt32(arr[j - 1]),j - 1] + 1; 
            } 
        } 
        return dp[k,n]; 
    } 
    
    // Driver code 
    public static void Main() 
    { 
        ArrayList A = new ArrayList(); 
        A.Add(1); 
        A.Add(2); 
        A.Add(3); 
        A.Add(4); 
        int k = 10; 
        Console.WriteLine(productSubSeqCount(A, k)); 
    } 
} 

// This Code is contributed Ryuga 
JavaScript
<script>
    // Javascript program to find number of subarrays 
    // having product less than k.
    
    // Function to count numbers of such 
    // subsequences having product less than k.
    function productSubSeqCount(arr, k)
    {
        let n = arr.length;
        let dp = new Array(k + 1);
        for (let i = 0; i < k + 1; i++)
        {
            dp[i] = new Array(n + 1);
            for (let j = 0; j < n + 1; j++)
            {
                dp[i][j] = 0;
            }
        }
          
        for (let i = 1; i <= k; i++) {
            for (let j = 1; j <= n; j++) {
          
                // number of subsequence using j-1 terms
                dp[i][j] = dp[i][j - 1];
          
                // if arr[j-1] > i it will surely make 
                // product greater thus it won't contribute
                // then
                if (arr[j-1] <= i && arr[j-1] > 0)
      
                    // number of subsequence using 1 to j-1
                    // terms and j-th term
                    dp[i][j] += dp[parseInt(i/arr[j - 1], 10)][j - 1] + 1;
            }
        }
        return dp[k][n];
    }
    
    let A = [1, 2, 3, 4];
    let k = 10;
    document.write(productSubSeqCount(A, k));
    
    // This code is contributed by suresh07.
</script>
Python3
# Python3 program to find 
# number of subarrays having 
# product less than k. 
def productSubSeqCount(arr, k):
    n = len(arr)
    dp = [[0 for i in range(n + 1)]
             for j in range(k + 1)]
    for i in range(1, k + 1):
        for j in range(1, n + 1):
            
            # number of subsequence
            # using j-1 terms 
            dp[i][j] = dp[i][j - 1]
            
            # if arr[j-1] > i it will 
            # surely make product greater
            # thus it won't contribute then 
            if arr[j - 1] <= i and arr[j - 1] > 0:
                
                # number of subsequence
                # using 1 to j-1 terms
                # and j-th term
                dp[i][j] += dp[i // arr[j - 1]][j - 1] + 1
    return dp[k][n]

# Driver code 
A = [1,2,3,4]
k = 10
print(productSubSeqCount(A, k))

# This code is contributed 
# by pk_tautolo

Output
11

Time Complexity: O(K*N)
Auxiliary Space: O(K*N)
 



Similar Reads

Count of alphabets having ASCII value less than and greater than k
Given a string, the task is to count the number of alphabets having ASCII values less than and greater than or equal to a given integer k. Examples: Input: str = "GeeksForGeeks", k = 90Output:3, 10G, F, G have ascii values less than 90.e, e, k, s, o, r, e, e, k, s have ASCII values greater than or equal to 90 Input: str = "geeksforgeeks", k = 90Out
11 min read
Count of indices in Array having all prefix elements less than all in suffix
Given an array arr[], the task is to calculate the total number of indices where all elements in the left part is less than all elements in the right part of the array. Examples: Input: arr[] = {1, 5, 4, 2, 3, 8, 7, 9}Output: 3Explanation: Lets consider left part = [1], right part = [5, 4, 2, 3, 8, 7, 9]Here, leftMax (1) < rightMin (2). So, it c
12 min read
Find all possible subarrays having product less than or equal to K
Given an array arr[], the task is to print all possible subarrays having a product of its elements less than or equal to K. Input: arr[] = {2, 1, 3, 4, 5, 6, 2}, K = 10 Output: [[2], [1], [2, 1], [3], [1, 3], [2, 1, 3], [4], [5], [6], [2]] Explanation: All possible subarrays having product ? K are {2}, {1}, {2, 1}, {3}, {1, 3}, {2, 1, 3}, {4}, {5},
13 min read
Maximum product from array such that frequency sum of all repeating elements in product is less than or equal to 2 * k
Given an array arr[] and an integer k, the task is to find the maximum product from the array such that the frequency sum of all repeating elements in the product is â‰Ī 2 * k, where frequency sum is the sum of frequencies of all the elements in the product that appear more than once. For example, if we choose a product 1 * 1 * 2 * 3 * 4 * 5 * 6 * 6
7 min read
Count of subsequences in an array with sum less than or equal to X
Given an integer array arr[] of size N and an integer X, the task is to count the number of subsequences in that array such that its sum is less than or equal to X. Note: 1 <= N <= 1000 and 1 <= X <= 1000, where N is the size of the array. Examples: Input : arr[] = {84, 87, 73}, X = 100 Output : 3 Explanation: The three subsequences wit
13 min read
Count of subsequences with sum two less than the array sum
Given an array vec[] of size N of non-negative integers. The task is to count the number of subsequences with the sum equal to S - 2 where S is the sum of all the elements of the array. Examples: Input: vec[] = {2, 0, 1, 2, 1}, N=5Output: 6Explanation: {2, 0, 1, 1}, {2, 1, 1}, {2, 0, 2}, {2, 2}, {0, 1, 2, 1}, {1, 2, 1} Input: vec[] = {2, 0, 2, 3, 1
12 min read
Number of subarrays having product less than K
Given an array of positive numbers, calculate the number of possible contiguous subarrays having product lesser than a given number K. Examples : Input : arr[] = [1, 2, 3, 4] K = 10Output : 7The subarrays are {1}, {2}, {3}, {4}, {1, 2}, {1, 2, 3} and {2, 3} Input : arr[] = [1, 9, 2, 8, 6, 4, 3] K = 100Output : 16 Input : arr[] = [10, 5, 2, 6] K = 1
13 min read
Find minimum integer greater than B that is product of two values less than A
Given 2 positive integers A and B, the task is to find the minimum possible integer C, which is greater than or equal to B and is a product of two positive integers, both of which are less than or equal to A. Examples: Input: A = 5, B = 7Output: 8Explanation: 8 can be represented as a product of 2 positive integers less than 5. i.e. 2*4 = 8. Also,
6 min read
Count of elements having Euler's Totient value one less than itself
Given an array arr[] of N integers, and a range L to R, the task is to find the total number of elements in the array from index L to R that satisfies the following condition: [Tex]F(arr[i]) = arr[i] - 1 [/Tex] where F(x) is Euler's Totient Function. Examples: Input: arr[] = {2, 4, 5, 8}, L = 1, R = 3 Output: 2 Explanation: Here in the given range,
9 min read
Count pairs having Bitwise XOR less than K from given array
Given an array arr[]of size N and an integer K, the task is to count the number of pairs from the given array such that the Bitwise XOR of each pair is less than K. Examples: Input: arr = {1, 2, 3, 5} , K = 5 Output: 4 Explanation: Bitwise XOR of all possible pairs that satisfy the given conditions are: arr[0] ^ arr[1] = 1 ^ 2 = 3 arr[0] ^ arr[2] =
15+ min read
Sum of all array elements less than X and greater than Y for Q queries
Given a sorted array arr[], and a set Q having M queries, where each query has values X and Y, the task is to find the sum of all integers less than X and greater than Y present in the array. Note: X and Y may or may not be present in the array. Examples: Input: arr[] = [3 5 8 12 15], Q = {{5, 12}, {4, 8}} Output: 18 30 Explanation: For query 1, X
9 min read
For each A[i] find smallest subset with all elements less than A[i] sum more than B[i]
Given two arrays A[] and B[] of N integers, the task is to find for each element A[i], the size of the smallest subset S of indices, such that : Each value corresponding to the indices in subset S is strictly less than A[i].Sum of elements corresponding to the indices in B is strictly greater than B[i]. Examples: Input: N = 5, A = {3, 2, 100, 4, 5}
10 min read
Construct array having X subsequences with maximum difference smaller than d
Given two numbers X and d where X represents the number of non empty subsequences and d represents the difference. Output an array of size N having non empty subsequences equal to X where difference between maximum element and minimum element of each subsequence should be less than d. Constraints: 1 ? N ? 500 1 ? X ? 109 Examples: Input : X = 10, d
10 min read
Count of all subsequences having adjacent elements with different parity
Given an array arr[] of size N, the task is to find the number of non-empty subsequences from the given array such that no two adjacent elements of the subsequence have the same parity. Examples: Input: arr[] = [5, 6, 9, 7] Output: 9 Explanation: All such subsequences of given array will be {5}, {6}, {9}, {7}, {5, 6}, {6, 7}, {6, 9}, {5, 6, 9}, {5,
9 min read
Count pairs in a sorted array whose product is less than k
Given a sorted integer array and number k, the task is to count pairs in an array whose product is less than x. Examples: Input: A = {2, 3, 5, 6}, k = 16 Output: 4 Pairs having product less than 16: (2, 3), (2, 5), (2, 6), (3, 5) Input: A = {2, 3, 4, 6, 9}, k = 20 Output: 6 Pairs having product less than 20: (2, 3), (2, 4), (2, 6), (2, 9), (3, 4),
12 min read
Count ordered pairs with product less than N
Given an integer N. The task is to count the number of ordered pairs (a, b) such that [Tex]a * b < N [/Tex].Examples: Input: N = 5 Output: 8 Ordered Pairs are = (1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (3, 1), (4, 1). Input: N = 1000 Output: 7053 Naive Approach: Run two for loops upto N - 1 and count ordered pairs whose products are less
5 min read
Count number less than N which are product of perfect squares
Given an Integer N. The task is to count numbers P less than N such that P is a product of two distinct perfect squares. Examples: Input : N = 36 Output : 5 Numbers are 4 = 12 * 22, 9 = 12 * 32, 16 = 12 * 42, 25 = 12 * 52, 36 = 12 * 62Input : N = 1000000 Output : 999 Approach: Let us consider a number P = (a2 * b2) such that P <= N. So we have (
3 min read
Count the number of unordered triplets with elements in increasing order and product less than or equal to integer X
Given an array A[] and an integer X. Find the number of unordered triplets (i, j, k) such that A[i] < A[j] < A[k] and A[i] * A[j] * A[k] <= X. Examples: Input: A = [3, 2, 5, 7], X = 42 Output: 2 Explanation: Triplets are : (1, 0, 2) => 2 < 3 < 5, 2 * 3 * 5 < = 42(1, 0, 3) => 2 < 3 < 7, 2 * 3 * 7 < = 42 Input: A = [3
11 min read
Count Subarrays with product of sum and subarray length less than K
Given an array of positive elements arr[] of length N, the task is to count all the subarrays such that the product of the subarray sum and length of the subarray should be strictly less than K. Examples: Input: arr[] = {6, 2, 1, 4, 3}, K = 10Output: 6Explanation: There are six valid subarrays: {6}, {2}, {1}, {4}, {3}, {2, 1} Input: arr[] = {1, 4,
13 min read
Sum and Product of all the nodes which are less than K in the linked list
Given a Linked List and a key K. The task is to calculate the sum and product all the nodes from the list that are lesser than the key K. Examples: Input: 12 -> 15 -> 9 -> 11 -> 5 -> 6, K = 9 Output: Sum = 11, Product = 30 Input: 13 -> 4 -> 16 -> 9 -> 22 -> 45 -> 5 -> 16 -> 6, K = 10 Output: Sum = 24, Product
11 min read
Find product of all elements at indexes which are factors of M for all possible sorted subsequences of length M
Given an array arr[] of N distinct integers and a positive integer M, the task is to find the product of all the elements at the indexes which are the factors of M for all the possible sorted subsequences of length M from the given array arr[].Note: The product may be very large, take modulo to 109 + 7. Examples: Input: arr[] = {4, 7, 5, 9, 3}, M =
13 min read
Largest number less than X having at most K set bits
Given an integer X > 1 and an integer K > 0, the task is to find the greatest odd number < X such that the number of 1's in its binary representation is at most K. Examples: Input: X = 10, K = 2 Output: 10 Input: X = 29, K = 2 Output: 24 Naive Approach: Starting from X - 1 check all the numbers below X which have at most K set bits, the fi
4 min read
Maximum sum subarray having sum less than given sum using Set
Given an array arr[] of length N and an integer K, the task is the find the maximum sum subarray with a sum less than K.Note: If K is less than the minimum element, then return INT_MIN. Examples: Input: arr[] = {-1, 2, 2}, K = 4 Output: 3 Explanation: The subarray with maximum sum which is less than 4 is {-1, 2, 2}. The subarray {2, 2} has maximum
7 min read
Largest subset having with sum less than equal to sum of respective indices
Given an array arr[], the task is to find the length of the largest subset with the sum of elements less than or equal to the sum of its indexes(1-based indexing). Examples: Input: arr[] = {1, 7, 3, 5, 9, 6, 6} Output: 5 Explanation: Largest Subset is {1, 3, 5, 6, 6} Sum of indexes = 1 + 3 + 4 + 6 + 7 = 21 Sum of elements = 1 + 3 + 5 + 6 + 6 = 21 I
8 min read
Node having maximum number of nodes less than its value in its subtree
Given a Binary Tree, the task is to find the node from the given tree which has the maximum number of nodes in its subtree with values less than the value of that node. In the case of multiple possible nodes with the same number of maximum nodes, then return any such node. Examples: Input: 4 / \ 6 10 / \ / \2 3 7 14 / 5 Output: 6Explanation:Node wi
10 min read
Find the pairs of IDs from two arrays having sum less than target closest to it
Given two arrays arr1[] and arr2[] of pairs of the form {ID, value} of size N and M respectively and an integer target, the task is to find all the pairs of IDs from both the arrays such that the sum of the values of the pairs is maximum and has a value at most M. Examples: Input: arr1[] = [[1, 2000], [2, 3000], [3, 2000]], arr2[] = [[1, 2500], [2,
9 min read
Longest non-decreasing subsequence having difference between adjacent elements less than D
Given an array arr[] of N integers and an integer D, the task is to find the length of the longest non-decreasing subsequence such that the difference between every adjacent element is less than D. Examples: Input: arr[] = {1, 3, 2, 4, 5}, D = 2Output: 3Explanation:Consider the subsequence as {3, 4, 5}, which is of maximum length = 3 satisfying the
6 min read
Largest number less than equal to N having exactly K set bits
Given two positive integers N and K, we need to determine if there exists a positive integer X less than or equal to N such that the number of 1s in the binary representation of X is equal to k (i.e., f(X) = K). If such an X exists, we also need to find the maximum value of X and print -1 if there is no such positive integer X. Constraints: 1 <=
13 min read
First element of every K sets having consecutive elements with exactly K prime factors less than N
Given two integers N and K, the task is to find the first element for every set of K consecutive elements which have exactly K prime factors and are less than N. Examples: Input: N = 30, K = 2 Output: 14 20 21 Explanation: Numbers which have prime factors equals to 2 less than 30 = { 14, 15, 18, 20, 21, 22, 24, 26, 28 }. In the above examples, for
11 min read
Longest sub-string having frequency of each character less than equal to k
Given a string str of length n. The problem is to find the length of the longest sub-string in str having frequency of each character less than equal to the given value k. Examples : Input : str = "babcaag", k = 1 Output : 3 abc and bca are the two longest sub-strings having frequency of each character in them less than equal to '1'. Input : str =
10 min read