Maximum product subset of an array in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find maximum product subset of an array.

For this we will be provided with an array containing positive and negative values. Our task is to find the maximum product for a subset of the array.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int maxProductSubset(int a[], int n) {
   if (n == 1)
      return a[0];
      int max_neg = INT_MIN;
      int count_neg = 0, count_zero = 0;
      int prod = 1;
   for (int i = 0; i < n; i++) {
      //multiplying 0 is not useful
      if (a[i] == 0) {
         count_zero++;
         continue;
      }
      if (a[i] < 0) {
         count_neg++;
         max_neg = max(max_neg, a[i]);
      }
      prod = prod * a[i];
   }
   if (count_zero == n)
      return 0;
   if (count_neg & 1) {
      if (count_neg == 1 &&
         count_zero > 0 &&
         count_zero + count_neg == n)
         return 0;
      prod = prod / max_neg;
   }
   return prod;
}
int main() {
   int a[] = { -1, -1, -2, 4, 3 };
   int n = sizeof(a) / sizeof(a[0]);
   cout << maxProductSubset(a, n);
   return 0;
}

Output

24
raja
Published on 03-Jul-2020 11:22:51
Advertisements