VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-product-subset-array/

⇱ Maximum product subset of an array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum product subset of an array

Last Updated : 1 Jun, 2026

Given an array a, we need to find the maximum product possible with the subset of elements present in the array.

  1. The maximum product can be of a single element also.
  2. Since the product can be large, return it modulo 109 + 7.

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

[Naive Approach] Generate All Subsets - O(2ⁿ) Time and O(n) Space

The idea is to recursively generate every possible non-empty subsequence of the array. For each element, there are two choices: either include it in the current subsequence or exclude it. While exploring all possible combinations, the product of the selected elements is maintained. Whenever the end of the array is reached, the product of the current non-empty subsequence is compared with the maximum product found so far.

  • Start recursion from index 0
  • Consider two choices for every element: Include it in the subsequence and Exclude it from the subsequence
  • Maintain the product of selected elements
  • When all elements are processed, If the subsequence is non-empty, update the maximum product
  • Return the maximum product found

Output
24

[Expected Approach] Using Greedy Traversal - O(n) Time and O(1) Space

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 or maximum value among all negatives.
  • If there are zeros, the result is computed same way as above ignoring zeros except one case. The exceptional case is when there is one negative number and all other elements are 0. In this case, the result is 0.

Output
24
Comment
Article Tags: