The Wayback Machine - https://web.archive.org/web/20240623215315/https://www.geeksforgeeks.org/minimum-product-subset-array/
Open In App

Minimum product subset of an array

Last Updated : 16 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

INTRODUCTION:

The minimum product subset of an array refers to a subset of elements from the array such that the product of the elements in the subset is minimized. To find the minimum product subset, various algorithms can be used, such as greedy algorithms, dynamic programming, and branch and bound. The choice of algorithm depends on the specific constraints and requirements of the problem.

  1. One common algorithm used to find the minimum product subset of an array is the greedy algorithm. The basic idea of this algorithm is to start with the first element of the array and add the next element to the subset only if it will result in a smaller product. The advantage of this algorithm is its simplicity and ease of implementation. However, the greedy algorithm may not always produce the optimal solution and can be very slow for large arrays.
  2. Another algorithm used for this problem is dynamic programming. The dynamic programming algorithm divides the problem into subproblems and solves each subproblem only once, using the solutions of smaller subproblems to find the solution for larger ones. This can lead to significant time and space savings. The advantage of dynamic programming is that it always provides the optimal solution, but it can be more complex to implement compared to the greedy algorithm.
  3. Branch and bound is another algorithm that can be used to find the minimum product subset of an array. This algorithm involves searching for a solution by branching into multiple possibilities and bounding the search to only consider valid solutions. The advantage of this algorithm is that it provides the optimal solution and can be faster than other algorithms for certain cases. However, it can also be more complex to implement and may require more time and space compared to other algorithms.

In conclusion, the choice of algorithm depends on the specific constraints and requirements of the problem, such as the size of the array, the required solution accuracy, and the available computational resources.

Given 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.

Implementation:

C++




// CPP program to find maximum product of
// a subset.
#include <bits/stdc++.h>
using namespace std;
 
int minProductSubset(int a[], int n)
{
    if (n == 1)
        return a[0];
    // Find count of negative numbers, count of zeros,
    // maximum valued negative number, minimum valued
    // positive number and product of non-zero numbers
    int max_neg = INT_MIN, min_pos = INT_MAX, count_neg = 0,
        count_zero = 0, prod = 1;
    for (int i = 0; i < n; i++) {
        // If number is 0, we don't multiply it with
        // product.
        if (a[i] == 0) {
            count_zero++;
            continue;
        }
        // Count negatives and keep track of maximum valued
        // negative.
        if (a[i] < 0) {
            count_neg++;
            max_neg = max(max_neg, a[i]);
        }
        // Track minimum positive number of array
        if (a[i] > 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;
}
 
int main()
{
    int a[] = { -1, -1, -2, 4, 3 };
    int n = sizeof(a) / sizeof(a[0]);
    cout << minProductSubset(a, n);
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta


C




// C program to find maximum product of
// a subset.
#include <limits.h>
#include <stdio.h>
 
// Find maximum between two numbers.
int max(int num1, int num2)
{
    return (num1 > num2) ? num1 : num2;
}
 
// Find minimum between two numbers.
int min(int num1, int num2)
{
    return (num1 > num2) ? num2 : num1;
}
 
int minProductSubset(int a[], int n)
{
    if (n == 1)
        return a[0];
    // Find count of negative numbers, count of zeros,
    // maximum valued negative number, minimum valued
    // positive number and product of non-zero numbers
    int max_neg = INT_MIN, min_pos = INT_MAX, count_neg = 0,
        count_zero = 0, prod = 1;
    for (int i = 0; i < n; i++) {
        // If number is 0, we don't multiply it with
        // product.
        if (a[i] == 0) {
            count_zero++;
            continue;
        }
        // Count negatives and keep track of maximum valued
        // negative.
        if (a[i] < 0) {
            count_neg++;
            max_neg = max(max_neg, a[i]);
        }
        // Track minimum positive number of array
        if (a[i] > 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;
}
 
int main()
{
    int a[] = { -1, -1, -2, 4, 3 };
    int n = sizeof(a) / sizeof(a[0]);
    printf("%d", minProductSubset(a, n));
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta


Java




// Java program to find maximum product of
// a subset.
class GFG {
 
    static int minProductSubset(int a[], int n)
    {
        if (n == 1)
            return a[0];
 
        // Find count of negative numbers,
        // count of zeros, maximum valued
        // negative number, minimum valued
        // positive number and product of
        // non-zero numbers
        int negmax = Integer.MIN_VALUE;
        int posmin = Integer.MAX_VALUE;
        int count_neg = 0, count_zero = 0;
        int product = 1;
 
        for (int i = 0; i < n; i++) {
 
            // if number is zero,count it
            // but dont multiply
            if (a[i] == 0) {
                count_zero++;
                continue;
            }
 
            // count the negative numbers
            // and find the max negative number
            if (a[i] < 0) {
                count_neg++;
                negmax = Math.max(negmax, a[i]);
            }
 
            // find the minimum positive number
            if (a[i] > 0 && a[i] < posmin)
                posmin = a[i];
 
            product *= a[i];
        }
 
        // if there are all zeroes
        // or zero is present but no
        // negative number is present
        if (count_zero == n
            || (count_neg == 0 && count_zero > 0))
            return 0;
 
        // If there are all positive
        if (count_neg == 0)
            return posmin;
 
        // If there are even number except
        // zero of negative numbers
        if (count_neg % 2 == 0 && count_neg != 0) {
 
            // Otherwise result is product of
            // all non-zeros divided by maximum
            // valued negative.
            product = product / negmax;
        }
 
        return product;
    }
 
    // main function
    public static void main(String[] args)
    {
 
        int a[] = { -1, -1, -2, 4, 3 };
        int n = 5;
 
        System.out.println(minProductSubset(a, n));
    }
}
 
// This code is contributed by Arnab Kundu.


Python3




# Python3 program to find maximum
# product of a subset.
 
# def to find maximum
# product of a subset
 
 
def minProductSubset(a, n):
    if (n == 1):
        return a[0]
 
    # Find count of negative numbers,
    # count of zeros, maximum valued
    # negative number, minimum valued
    # positive number and product
    # of non-zero numbers
    max_neg = float('-inf')
    min_pos = float('inf')
    count_neg = 0
    count_zero = 0
    prod = 1
    for i in range(0, n):
 
        # If number is 0, we don't
        # multiply it with product.
        if (a[i] == 0):
            count_zero = count_zero + 1
            continue
 
        # Count negatives and keep
        # track of maximum valued
        # negative.
        if (a[i] < 0):
            count_neg = count_neg + 1
            max_neg = max(max_neg, a[i])
 
        # Track minimum positive
        # number of array
        if (a[i] > 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 or (count_neg == 0
                            and 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) == 0 and
            count_neg != 0):
 
        # Otherwise result is product of
        # all non-zeros divided by
        # maximum valued negative.
        prod = int(prod / max_neg)
 
    return prod
 
 
# Driver code
a = [-1, -1, -2, 4, 3]
n = len(a)
print(minProductSubset(a, n))
# This code is contributed by
# Manish Shaw (manishshaw1)


C#




// C# program to find maximum product of
// a subset.
using System;
 
public class GFG {
 
    static int minProductSubset(int[] a, int n)
    {
        if (n == 1)
            return a[0];
 
        // Find count of negative numbers,
        // count of zeros, maximum valued
        // negative number, minimum valued
        // positive number and product of
        // non-zero numbers
        int negmax = int.MinValue;
        int posmin = int.MinValue;
        int count_neg = 0, count_zero = 0;
        int product = 1;
 
        for (int i = 0; i < n; i++) {
 
            // if number is zero, count it
            // but dont multiply
            if (a[i] == 0) {
                count_zero++;
                continue;
            }
 
            // count the negative numbers
            // and find the max negative number
            if (a[i] < 0) {
                count_neg++;
                negmax = Math.Max(negmax, a[i]);
            }
 
            // find the minimum positive number
            if (a[i] > 0 && a[i] < posmin) {
                posmin = a[i];
            }
 
            product *= a[i];
        }
 
        // if there are all zeroes
        // or zero is present but no
        // negative number is present
        if (count_zero == n
            || (count_neg == 0 && count_zero > 0))
            return 0;
 
        // If there are all positive
        if (count_neg == 0)
            return posmin;
 
        // If there are even number except
        // zero of negative numbers
        if (count_neg % 2 == 0 && count_neg != 0) {
 
            // Otherwise result is product of
            // all non-zeros divided by maximum
            // valued negative.
            product = product / negmax;
        }
 
        return product;
    }
 
    // main function
    public static void Main()
    {
 
        int[] a = new int[] { -1, -1, -2, 4, 3 };
        int n = 5;
 
        Console.WriteLine(minProductSubset(a, n));
    }
}
 
// This code is contributed by Ajit.


PHP




<?php
// PHP program to find maximum
// product of a subset.
 
// Function to find maximum
// product of a subset
function minProductSubset($a, $n)
{
     
    if ($n == 1)
        return $a[0];
 
    // Find count of negative numbers,
    // count of zeros, maximum valued
    // negative number, minimum valued
    // positive number and product
    // of non-zero numbers
    $max_neg = PHP_INT_MIN;
    $min_pos = PHP_INT_MAX;
    $count_neg = 0; $count_zero = 0;
    $prod = 1;
    for ($i = 0; $i < $n; $i++)
    {
 
        // If number is 0, we don't
        // multiply it with product.
        if ($a[$i] == 0)
        {
            $count_zero++;
            continue;
        }
 
        // Count negatives and keep
        // track of maximum valued
        // negative.
        if ($a[$i] < 0)
        {
            $count_neg++;
            $max_neg = max($max_neg, $a[$i]);
        }
 
        // Track minimum positive
        // number of array
        if ($a[$i] > 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.
?>


Javascript




<script>
 
// Javascript program to find maximum
// product of a subset.
function minProductSubset(a, n)
{
    if (n == 1)
        return a[0];
 
    // Find count of negative numbers,
    // count of zeros, maximum valued
    // negative number, minimum valued
    // positive number and product of
    // non-zero numbers
    let negmax = Number.MAX_VALUE;
    let posmin = Number.NEGATIVE_INFINITY;
    let count_neg = 0, count_zero = 0;
    let product = 1;
 
    for(let i = 0; i < n; i++)
    {
         
        // If number is zero, count it
        // but dont multiply
        if (a[i] == 0)
        {
            count_zero++;
            continue;
        }
 
        // Count the negative numbers
        // and find the max negative number
        if (a[i] < 0)
        {
            count_neg++;
            negmax = Math.max(negmax, a[i]);
        }
 
        // Find the minimum positive number
        if (a[i] > 0 && a[i] < posmin)
        {
            posmin = a[i];
        }
 
        product *= a[i];
    }
 
    // If there are all zeroes
    // or zero is present but no
    // negative number is present
    if (count_zero == n || (count_neg == 0 &&
        count_zero > 0))
        return 0;
 
    // If there are all positive
    if (count_neg == 0)
        return posmin;
 
    // If there are even number except
    // zero of negative numbers
    if (count_neg % 2 == 0 && count_neg != 0)
    {
 
        // Otherwise result is product of
        // all non-zeros divided by maximum
        // valued negative.
        product = parseInt(product / negmax, 10);
    }
    return product;
}
 
// Driver code
let a = [ -1, -1, -2, 4, 3 ];
let n = 5;
 
document.write(minProductSubset(a, n));
 
</script>


Output

-24

Complexity Analysis:

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


Previous Article
Next Article

Similar Reads

Split Array into K non-overlapping subset such that maximum among all subset sum is minimum
Given an array arr[] consisting of N integers and an integer K, the task is to split the given array into K non-overlapping subsets such that the maximum among the sum of all subsets is minimum. Examples: Input: arr[] = {1, 7, 9, 2, 12, 3, 3}, M = 3Output: 13Explanation:One possible way to split the array into 3 non-overlapping subsets is {arr[4],
7 min read
Maximum size of subset such that product of all subset elements is a factor of N
Given an integer N and an array arr[] having M integers, the task is to find the maximum size of the subset such that the product of all elements of the subset is a factor of N. Examples: Input: N = 12, arr[] = {2, 3, 4}Output: 2Explanation: The given array 5 subsets such that the product of all elements of the subset is a factor of 12. They are {2
6 min read
Sum of maximum and minimum of Kth subset ordered by increasing subset sum
Given an integer N and a set of all non-negative powers of N as S = {N0, N1, N2, N3, ... }, arrange all non-empty subsets of S in increasing order of subset-sum. The task is to find the sum of the greatest and smallest elements of the Kth subset from that ordering. Examples: Input: N = 4, K = 3Output: 5Explanation: S = {1, 4, 16, 64, ...}.Therefore
7 min read
Minimum Subset sum difference problem with Subset partitioning
Given a set of N integers with up to 40 elements, the task is to partition the set into two subsets of equal size (or the closest possible), such that the difference between the sums of the subsets is minimized. If the size of the set is odd, one subset will have one more element than the other. If the size is even, both subsets will have the same
13 min read
Find a non empty subset in an array of N integers such that sum of elements of subset is divisible by N
Given an array of N integers, the task is to find a non-empty subset such that the sum of elements of the subset is divisible by N. Output any such subset with its size and the indices(1-based indexing) of elements in the original array if it exists. Prerequisites: Pigeonhole PrincipleExamples: Input: arr[] = { 2, 3, 7, 1, 9 } Output: 2 1 2 The req
8 min read
Largest possible Subset from an Array such that no element is K times any other element in the Subset
Given an array arr[] consisting of N distinct integers and an integer K, the task is to find the maximum size of a subset possible such that no element in the subset is K times any other element of the subset(i.e. no such pair {n, m} should be present in the subset such that either m = n * K or n = m * K). Examples: Input: arr[] = {2, 8, 6, 5, 3},
7 min read
Find maximum subset sum formed by partitioning any subset of array into 2 partitions with equal sum
Given an array A containing N elements. Partition any subset of this array into two disjoint subsets such that both the subsets have an identical sum. Obtain the maximum sum that can be obtained after partitioning. Note: It is not necessary to partition the entire array, that is any element might not contribute to any of the partition. Examples: In
15+ min read
C++ 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
3 min read
Java 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
3 min read
Python 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
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg