Given an array a, we have to find the minimum product possible with the subset of elements present in the array. The minimum product can be a single element also.
Examples:Â
Input : a[] = { -1, -1, -2, 4, 3 }
Output : -24
Explanation : Minimum product will be ( -2 * -1 * -1 * 4 * 3 ) = -24
Input : a[] = { -1, 0 }
Output : -1
Explanation : -1(single element) is minimum product possible
Input : a[] = { 0, 0, 0 }
Output : 0
A simple solution is to generate all subsets, find the product of every subset and return the minimum product.
A better solution is to use the below facts. Â
- If there are even number of negative numbers and no zeros, the result is the product of all except the largest valued negative number.
- If there are an odd number of negative numbers and no zeros, the result is simply the product of all.
- If there are zeros and positive, no negative, the result is 0. The exceptional case is when there is no negative number and all other elements positive then our result should be the first minimum positive number.
Python3
def minProductSubset(a, n):
if (n = = 1 ):
return a[ 0 ]
max_neg = float ( '-inf' )
min_pos = float ( 'inf' )
count_neg = 0
count_zero = 0
prod = 1
for i in range ( 0 , n):
if (a[i] = = 0 ):
count_zero = count_zero + 1
continue
if (a[i] < 0 ):
count_neg = count_neg + 1
max_neg = max (max_neg, a[i])
if (a[i] > 0 ):
min_pos = min (min_pos, a[i])
prod = prod * a[i]
if (count_zero = = n or (count_neg = = 0
and count_zero > 0 )):
return 0
if (count_neg = = 0 ):
return min_pos
if ((count_neg & 1 ) = = 0 and
count_neg ! = 0 ):
prod = int (prod / max_neg)
return prod
a = [ - 1 , - 1 , - 2 , 4 , 3 ]
n = len (a)
print (minProductSubset(a, n))
|
Time Complexity : O(n)Â
Auxiliary Space : O(1)
Please refer complete article on Minimum product subset of an array for more details!
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
20 Jan, 2022
Like Article
Save Article