Maximum product subset of an array in C++ program

C++Server Side ProgrammingProgramming

In the problem, we are given an array arr[] of n integer values. Our task is to create a program to find the Maximum product subset of an array.

Problem Description − Here, we need to calculate the maximum possible product of a subset of elements of an array.

Subset − An array sub[] is a subset of array arr[] if all elements of sub[] are present in arr[].

Let’s take an example to understand the problem,

Input

arr[] = {4, 5, 2, −1, 3}

Output

40

Explanation

Subset sub[] = {4, 5, 2}
Prod = 4*5*2 = 40

Solution Approach

A simple and easy approach to solve the problem is by creating all possible subsets of the array. Find their products and return the maximum of them.

This solution is easy to implement but requires nested loops making its complexity of the order of O(n2*n).

Try implementation here.

Effective solution is by calculating the number of negative’s(nofNeg) and zero’s(nof0) from the array and then calculate the maxProd based on these conditions.

Case 1(nof0 = 0 and nofNeg is even)− Consider all elements of the array to the product.

maxProd = arr[0] * arr[1] * … arr[n−1]

Case 2(nof0 = 0 and nofNeg is odd)− Consider all elements of the array except the largest negative element of the array (nearest to 0).

Case 3(nof0 != 0)− Leave all zeros of the array for the product. And take cases similar to cases 1 and 2.

Special Case − only one element except 0 is negative. maxProd = 0.

Algorithm

Initialise 

maxProd = 1;

Step 1

Loop the array and count, nof0(number of zeros) and
nofNeg(number of negatives), and find maxProd.
maxProd = maxProd*arr[i], i −> 0 to n−1

Step 2

consider the following cases −
Case 1− if(nofNeg%2 == 0): maxProd
Case 2− if(nofNeg%2 != 0): maxProd = maxProd/(largestNeg)
Case 3 − if(nof0 == (n-1) and nofNeg == 1), maxProd = 0.

Step 3

Print maxProd.

Example

Program to illustrate the working of our solution,

 Live Demo

#include <iostream>
using namespace std;
int findMaxSubsetProd(int arr[], int n){
   int larNeg = −1000;
   int nofNeg = 0, Nof0 = 0;
   int maxProd = 1;
   for (int i = 0; i < n; i++) {
      if (arr[i] == 0){
         Nof0++;
         continue;
      }
      else if (arr[i] < 0) {
         nofNeg++;
         if(larNeg < arr[i])
         larNeg = arr[i];
      }
      maxProd = maxProd * arr[i];
   }
   if(nofNeg%2 == 0){
      return maxProd;
   }
   else if(nofNeg%2 != 0)
      return (maxProd / larNeg);
   if(Nof0 == (n−1) and nofNeg == 1)
      return 0;
   return maxProd;
}
int main(){
   int arr[] = {4, −2, 5, −1, 3, −6};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout<<"The maximum product subset of an array is "<<findMaxSubsetProd(arr, n);
   return 0;
}

Output

The maximum product subset of an array is 720
raja
Published on 09-Dec-2020 12:14:01
Advertisements