
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Maximum product subset of an array in C++
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
#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
- Related Articles
- Maximum product subset of an array in C++ program
- Maximum sum of pairwise product in an array with negative allowed in C++
- Maximum sum of pairwise product in an array with negative allowed in C++ program
- Program to find maximum product of two distinct elements from an array in Python
- Maximum product of an increasing subsequence in C++
- Maximum product of an increasing subsequence in C++ Program
- Product of maximum in first array and minimum in second in C
- Find Two Array Elements Having Maximum Product in Java?
- Find a pair with maximum product in array of Integers in C++
- Maximum product quadruple (sub-sequence of size 4) in array in C++
- Maximum product of a triplet (subsequence of size 3) in array in C++
- Maximum product of an increasing subsequence of size 3 in C++
- Subset with maximum sum in JavaScript
- Find the sum of maximum difference possible from all subset of a given array in Python
- Find whether an array is subset of another array - Added Method 3 in C++

Advertisements