

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- Maximum product subset of an array in C++ program
- Maximum product of an increasing subsequence in C++
- Maximum sum of pairwise product in an array with negative allowed in C++
- Maximum product of an increasing subsequence in C++ Program
- 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 of size 3 in C++
- Maximum product of an increasing subsequence of size 3 in C++ program
- Product of maximum in first array and minimum in second in C
- Maximum product of a triplet (subsequence of size 3) in array in C++
- Find a pair with maximum product in array of Integers in C++
- Maximum product quadruple (sub-sequence of size 4) in array in C++
- Product of all other numbers an array in JavaScript
- Finding product of an array using recursion in JavaScript
- Maximum Product of Word Lengths in C++
Advertisements