![]() |
VOOZH | about |
Given an integer array arr[], determine the minimum possible product that can be obtained by multiplying the elements of any non-empty subset of the array.
Examples:
Input: arr[] = [1, 2, 3]
Output: 1
Explanation: The possible subset products are 1, 2, 3, 2, 3, 6, and 6. The minimum product is 1, obtained by selecting the subset [1].
Input: arr[] = [4, -2, 5]
Output: -40
Explanation: The minimum product is -40, obtained by selecting the subset [4, -2, 5].
Table of Content
The idea is to generate all possible non-empty subsets of the array using bit masking. For each subset, calculate the product of its elements and keep track of the minimum product obtained. Finally, return the smallest product among all subsets.
-40
Time Complexity: O(2 ^ n * n)
Auxiliary Space: O(1)
The idea is to use the properties of positive, negative, and zero elements. Compute the product of all non-zero elements and count the number of negative values. If the number of negatives is odd, the product of all non-zero elements gives the minimum product. If it is even, exclude the negative element with the smallest absolute value. Handle special cases involving only zeros or only positive numbers separately.
Let us understand with example:
Input: arr[] = [4, -2, 5]
-40
Time Complexity: O(n)
Auxiliary Space: O(1)