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

Maximum product subset of an array

Last Updated : 22 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array a, we have to find the maximum product possible with the subset of elements present in the array. The maximum product can be a single element also.
Examples: 

Input: a[] = { -1, -1, -2, 4, 3 }
Output: 24
Explanation : Maximum product will be ( -2 * -1 * 4 * 3 ) = 24

Input: a[] = { -1, 0 }
Output: 0
Explanation: 0(single element) is maximum product possible

Maximum product subset of an array using the count of positive and negative elements

  • The idea is to count the occurrence of positive and negative elements 
  • If there are even number of negative numbers and no zeros, the result is simply the product of all
  • If there are odd number of negative numbers and no zeros,then the result is the product of all except the negative integer with the least absolute value.
  • If there are zeros, the result is the product of all except these zeros with one exceptional case. The exceptional case is when there is one negative number and all other elements are 0. In this case, the result is 0.

Follow the steps mentioned below to implement the idea:

  • Create 3 variables count_neg , count_zero and prod , to store the occurrence of negative elements, zeros, and the product of the subset.
  • If count_neg is even then return prod.
  • If count_neg is odd then divide the smallest absolute negative element from prod and return prod.
  • If the array is filled with zeroes and negative elements then  return 0.

Below is the implementation of the above approach:
 

C++




// CPP program to find maximum product of
// a subset.
#include <bits/stdc++.h>
using namespace std;
 
int maxProductSubset(int a[], int n)
{
    if (n == 1)
        return a[0];
 
    // Find count of negative numbers, count
    // of zeros, negative number
    // with least absolute value
    // and product of non-zero numbers
    int max_neg = INT_MIN;
    int count_neg = 0, count_zero = 0;
    int 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 negative number
        // with least absolute value
        if (a[i] < 0) {
            count_neg++;
            max_neg = max(max_neg, a[i]);
        }
 
        prod = prod * a[i];
    }
 
    // If there are all zeros
    if (count_zero == n)
        return 0;
 
    // If there are odd number of
    // negative numbers
    if (count_neg & 1) {
 
        // Exceptional case: There is only
        // negative and all other are zeros
        if (count_neg == 1 &&
            count_zero > 0 &&
            count_zero + count_neg == n)
            return 0;
 
        // Otherwise result is product of
        // all non-zeros divided by
        //negative number with
        // least absolute value
        prod = prod / max_neg;
    }
 
    return prod;
}
 
// Driver Code
int main()
{
    int a[] = {  -1, -1, -2, 4, 3  };
    int n = sizeof(a) / sizeof(a[0]);
    cout << maxProductSubset(a, n);
    return 0;
}


C




// C program to find maximum product of
// a subset.
#include <stdio.h>
#include<math.h>
#include<stdlib.h>
 
int maxProductSubset(int a[], int n)
{
    if (n == 1)
        return a[0];
 
    // Find count of negative numbers, count
    // of zeros, negative number
    // with least absolute value
    // and product of non-zero numbers
    int max_neg = -100000009;
    int count_neg = 0, count_zero = 0;
    int 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 negative number
        // with least absolute value
        if (a[i] < 0) {
            count_neg++;
            max_neg = fmax(max_neg, a[i]);
        }
 
        prod = prod * a[i];
    }
 
    // If there are all zeros
    if (count_zero == n)
        return 0;
 
    // If there are odd number of
    // negative numbers
    if (count_neg & 1) {
 
        // Exceptional case: There is only
        // negative and all other are zeros
        if (count_neg == 1 &&
            count_zero > 0 &&
            count_zero + count_neg == n)
            return 0;
 
        // Otherwise result is product of
        // all non-zeros divided by
        //negative number with
        // least absolute value
        prod = prod / max_neg;
    }
 
    return prod;
}
 
// Driver Code
int main()
{
    int a[] = { -1, -1, -2, 4, 3 };
    int n = sizeof(a) / sizeof(a[0]);
    printf("%d",maxProductSubset(a, n));
    return 0;
}
 
// This code is contributed by rexomkar.


Java




// Java program to find maximum product of
// a subset.
 
class GFG {
 
    static int maxProductSubset(int a[], int n) {
        if (n == 1) {
            return a[0];
        }
 
        // Find count of negative numbers, count
        // of zeros, negative number
        // with least absolute value
        // and product of non-zero numbers
        int max_neg = Integer.MIN_VALUE;
        int count_neg = 0, count_zero = 0;
        int 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 negative number
            // with least absolute value.
            if (a[i] < 0) {
                count_neg++;
                max_neg = Math.max(max_neg, a[i]);
            }
 
            prod = prod * a[i];
        }
 
        // If there are all zeros
        if (count_zero == n) {
            return 0;
        }
 
        // If there are odd number of
        // negative numbers
        if (count_neg % 2 == 1) {
 
            // Exceptional case: There is only
            // negative and all other are zeros
            if (count_neg == 1
                    && count_zero > 0
                    && count_zero + count_neg == n) {
                return 0;
            }
 
            // Otherwise result is product of
            // all non-zeros divided by
            //negative number with
            // least absolute value.
            prod = prod / max_neg;
        }
 
        return prod;
    }
 
    // Driver Code
    public static void main(String[] args) {
        int a[] = {-1, -1, -2, 4, 3};
        int n = a.length;
        System.out.println(maxProductSubset(a, n));
 
    }
}
/* This JAVA code is contributed by Rajput-Ji*/


Python3




# Python3 program to find maximum product
# of a subset.
 
def maxProductSubset(a, n):
    if n == 1:
        return a[0]
 
    # Find count of negative numbers, count
    # of zeros, negative number
    # with least absolute value
    # and product of non-zero numbers
    max_neg = -999999999999
    count_neg = 0
    count_zero = 0
    prod = 1
    for i in range(n):
 
        # If number is 0, we don't
        # multiply it with product.
        if a[i] == 0:
            count_zero += 1
            continue
 
        # Count negatives and keep
        # track of negative number
        # with least absolute value.
        if a[i] < 0:
            count_neg += 1
            max_neg = max(max_neg, a[i])
 
        prod = prod * a[i]
 
    # If there are all zeros
    if count_zero == n:
        return 0
 
    # If there are odd number of
    # negative numbers
    if count_neg & 1:
 
        # Exceptional case: There is only
        # negative and all other are zeros
        if (count_neg == 1 and count_zero > 0 and
            count_zero + count_neg == n):
            return 0
 
        # Otherwise result is product of
        # all non-zeros divided
        # by negative number
        # with least absolute value
        prod = int(prod / max_neg)
 
    return prod
 
# Driver Code
if __name__ == '__main__':
    a = [ -1, -1, -2, 4, 3 ]
    n = len(a)
    print(maxProductSubset(a, n))
 
# This code is contributed by PranchalK


C#




// C# Java program to find maximum
// product of a subset.
using System;
                     
class GFG
{
 
static int maxProductSubset(int []a,
                            int n)
{
    if (n == 1)
    {
        return a[0];
    }
 
    // Find count of negative numbers,
    // count of zeros, negative number with
    // least absolute value and product of
    // non-zero numbers
    int max_neg = int.MinValue;
    int count_neg = 0, count_zero = 0;
    int 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 negative number with
        // least absolute value.
        if (a[i] < 0)
        {
            count_neg++;
            max_neg = Math.Max(max_neg, a[i]);
        }
 
        prod = prod * a[i];
    }
 
    // If there are all zeros
    if (count_zero == n)
    {
        return 0;
    }
 
    // If there are odd number of
    // negative numbers
    if (count_neg % 2 == 1)
    {
 
        // Exceptional case: There is only
        // negative and all other are zeros
        if (count_neg == 1 && count_zero > 0 &&
            count_zero + count_neg == n)
        {
            return 0;
        }
 
        // Otherwise result is product of
        // all non-zeros divided by negative
        // number with least absolute value.
        prod = prod / max_neg;
    }
 
    return prod;
}
 
// Driver code
public static void Main()
{
    int []a = {-1, -1, -2, 4, 3};
    int n = a.Length;
    Console.Write(maxProductSubset(a, n));
}
}
 
// This code is contributed by Rajput-Ji


PHP




<?php
// PHP program to find maximum
// product of a subset.
 
function maxProductSubset($a, $n)
{
    if ($n == 1)
        return $a[0];
 
    // Find count of negative numbers,
    // count of zeros, negative number
    // with least absolute value and product of
    // non-zero numbers
    $max_neg = PHP_INT_MIN;
    $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 negative number
        // with least absolute value.
        if ($a[$i] < 0)
        {
            $count_neg++;
            $max_neg = max($max_neg, $a[$i]);
        }
 
        $prod = $prod * $a[$i];
    }
 
    // If there are all zeros
    if ($count_zero == $n)
        return 0;
 
    // If there are odd number of
    // negative numbers
    if ($count_neg & 1)
    {
 
        // Exceptional case: There is only
        // negative and all other are zeros
        if ($count_neg == 1 &&
            $count_zero > 0 &&
            $count_zero + $count_neg == $n)
            return 0;
 
        // Otherwise result is product of
        // all non-zeros divided by negative
        // number with least absolute value.
        $prod = $prod / $max_neg;
    }
 
    return $prod;
}
 
// Driver Code
$a = array(-1, -1, -2, 4, 3 );
$n = sizeof($a);
echo maxProductSubset($a, $n);
 
// This code is contributed
// by Akanksha Rai
?>


Javascript




<script>
 
// JavaScript program to find maximum
// product of a subset.
 
function maxProductSubset(a, n)
{
    if (n == 1)
        return a[0];
 
    // Find count of negative numbers,
    // count of zeros, negative number
    // with least absolute value and product of
    // non-zero numbers
    let max_neg = Number.MIN_SAFE_INTEGER;
    let count_neg = 0; count_zero = 0;
    let prod = 1;
    for (let 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 negative number
        // with least absolute value.
        if (a[i] < 0)
        {
            count_neg++;
            max_neg = Math.max(max_neg, a[i]);
        }
 
        prod = prod * a[i];
    }
 
    // If there are all zeros
    if (count_zero == n)
        return 0;
 
    // If there are odd number of
    // negative numbers
    if (count_neg & 1)
    {
 
        // Exceptional case: There is only
        // negative and all other are zeros
        if (count_neg == 1 &&
            count_zero > 0 &&
            count_zero + count_neg == n)
            return 0;
 
        // Otherwise result is product of
        // all non-zeros divided by negative
        // number with least absolute value.
        prod = prod / max_neg;
    }
 
    return prod;
}
 
// Driver Code
let a = [-1, -1, -2, 4, 3 ];
let n = a.length;
document.write(maxProductSubset(a, n));
 
// This code is contributed
// by _saurabh_jaiswal
 
</script>


Output

24

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



Similar Reads

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
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
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
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
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
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
Maximum subset sum having difference between its maximum and minimum in range [L, R]
Given an array arr[] of N positive integers and a range [L, R], the task is to find the maximum subset-sum such that the difference between the maximum and minimum elements of the subset lies in the given range. Examples: Input: arr[] = {6, 5, 0, 9, 1}, L = 0, R = 3Output: 15Explanation: The subset {6, 9} of the given array has the difference betwe
9 min read
Minimum product subset of an array
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
13 min read
Minimize cost to split an array into K subsets such that the cost of each element is its product with its position in the subset
Given an array arr[] of size N and a positive integer K, the task is to find the minimum possible cost to split the array into K subsets, where the cost of ith element ( 1-based indexing ) of each subset is equal to the product of that element and i. Examples: Input: arr[] = { 2, 3, 4, 1 }, K = 3 Output: 11 Explanation: Split the array arr[] into K
7 min read
Practice Tags :
three90RightbarBannerImg