Given an integer array, find the maximum product of its elements among all its subsets.

For example,

Input:  nums[] = { -6, 4, -5, 8, -10, 0, 8 }
 
Output: The maximum product of a subset is 15360
 
The subset with the maximum product of its elements is { -6, 4, 8, -10, 8 }
 
 
 
Input:  nums[] = { 4, -8, 0, 8 }
 
Output: The maximum product of a subset is 32
 
The subset with the maximum product of its elements is { 4, 8 }

Practice this problem

1. Brute-Force Solution

A naive solution is to consider every subset and find the product of their elements. Finally, return the maximum product found among all subsets. The implementation can be seen below in C++, Java, and Python:

C++


Download  Run Code

Output:

The maximum product of a subset is 15360

Java


Download  Run Code

Output:

The maximum product of a subset is 15360

Python


Download  Run Code

Output:

The maximum product of a subset is 15360

The time complexity of the above solution is exponential and requires additional space for the recursion (call stack).

2. Linear-time Solution

We can solve this problem in linear time by finding a negative element with a minimum absolute value in the set. We also count the total number of negative elements present in the set. If the count of negative elements is odd, exclude that negative element (having minimum absolute value) from the subset; otherwise, consider it (since the multiplication of two negative numbers will give a positive number as output). We need to handle one more special case because 0 will never be part of the subset if at least one positive element or two negative elements are present in the subset. Rest all elements will form part of the subset.

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

The maximum product of a subset is 15360

Java


Download  Run Code

Output:

The maximum product of a subset is 15360

Python


Download  Run Code

Output:

The maximum product of a subset is 15360

The time complexity of the above solution is O(n) and doesn’t require any extra space, where n is the size of the input.