GeeksforGeeks App
Open App
Browser
Continue

Php Program for Minimum product subset of an array

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.

1. If there are even number of negative numbers and no zeros, the result is the product of all except the largest valued negative number.
2. If there are an odd number of negative numbers and no zeros, the result is simply the product of all.
3. 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.

PHP

 ` 0) ``            ``\$min_pos` `= min(``\$min_pos``, ``\$a``[``\$i``]); `` ` `        ``\$prod` `= ``\$prod` `* ``\$a``[``\$i``];``    ``}`` ` `    ``// If there are all zeros``    ``// or no negative number``    ``// present``    ``if` `(``\$count_zero` `== ``\$n` `|| ``       ``(``\$count_neg` `== 0 && ``        ``\$count_zero` `> 0))``        ``return` `0;`` ` `    ``// If there are all positive``    ``if` `(``\$count_neg` `== 0)``        ``return` `\$min_pos``;`` ` `    ``// If there are even number of``    ``// negative numbers and count_neg``    ``// not 0``    ``if` `(!(``\$count_neg` `& 1) && ``          ``\$count_neg` `!= 0)``    ``{`` ` `        ``// Otherwise result is product of``        ``// all non-zeros divided by maximum``        ``// valued negative.``        ``\$prod` `= ``\$prod` `/ ``\$max_neg``;``    ``}`` ` `    ``return` `\$prod``;``}`` ` `// Driver code``\$a` `= ``array``( -1, -1, -2, 4, 3 );``\$n` `= sizeof(``\$a``);``echo``(minProductSubset(``\$a``, ``\$n``));`` ` `// This code is contributed by Ajit.``?>`

Output:

`-24`

Time Complexity : O(n)
Auxiliary Space : O(1)

Please refer complete article on Minimum product subset of an array for more details!

My Personal Notes arrow_drop_up