![]() |
VOOZH | about |
Given an array arr[] of n elements. The task is to find the number of non-empty subsets whose product of elements is less than or equal to a given integer k.
Examples:
Input: arr[] = [2, 4, 5, 3], k = 12
Output: 8
Explanation: All possible subsets whose products are less than 12 are: (2), (4), (5), (3), (2, 4), (2, 5), (2, 3), (4, 3)Input: arr[] = [9, 8, 3], k = 2
Output: 0
Explanation: There are no subsets with products less than or equal to 2.
First of all, we simply divide the given array into two equal parts and after that, we generate all possible subsets for both parts of the array and store the value of the elements product for each subset separately into two containers (say subset1 & subset2). Then we combine the results of two halves to give a final answer. This technique is generally referred to as meet in the middle.
Algorithm:
- Divide array into two equal parts.
- Generate all subsets and for each subset calculate product of elements and store this to a container. Try this for both part of array.
- Sort both container which contains products of elements for each possible subsets.
- Traverse any one container and find upper-bound of element to find how many subsets are there whose product of elements is less than k.
Some key points to improve complexity:
15
Please refer to Number of subsets with product less than k using DP for Dynamic Programming solution.