C++ 中数组的最大乘积子集
在本文档中,我们将讨论一个程序,用于查找数组的最大乘积子集。
为此,我们将提供一个包含正值和负值的数组。我们的任务是为数组的子集找到最大乘积。
实例
#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; }
输出
24
广告