C++程序 最小乘积子集
给定一个数组a,我们必须找到该数组中元素子集的最小乘积。最小乘积也可以是单个元素。
例子:
输入: a[] = { -1, -1, -2, 4, 3 }
输出: -24
解释: 最小乘积为( -2 * -1 * -1 * 4 * 3 ) = -24
输入: a[] = { -1, 0 }
输出: -1
解释: -1(单个元素)是最小乘积
输入: a[] = { 0, 0, 0 }
输出: 0
一个简单的解决方案是生成所有子集,找到每个子集的乘积并返回最小乘积。
更好的解决方案是使用以下事实。
- 如果负数的数量为偶数且没有零,则结果是减去所有负数中的最大值。
- 如果负数的数量为奇数且没有零,则结果就是所有数字的乘积。
- 如果有零且所有数字都是正数,则结果为0。当没有负数并且所有其他数字都是正数时,我们的结果应为第一个最小的正数。
// CPP program to find maximum product of
// a subset.
#include <bits/stdc++.h>
using namespace std;
int minProductSubset(int a[], int n)
{
if (n == 1)
return a[0];
// Find count of negative numbers, count
// of zeros, maximum valued negative number,
// minimum valued positive number and product
// of non-zero numbers
int max_neg = INT_MIN;
int min_pos = INT_MAX;
int count_neg = 0, count_zero = 0;
int prod = 1;
for (int i = 0; i < n; i++) {
// If number is 0, we don't
// multiply it with product.
if (a[i] == 0) {
count_zero++;
continue;
}
// Count negatives and keep
// track of maximum valued negative.
if (a[i] < 0) {
count_neg++;
max_neg = max(max_neg, a[i]);
}
// Track minimum positive
// number of array
if (a[i] > 0)
min_pos = min(min_pos, a[i]);
prod = prod * a[i];
}
// If there are all zeros
// or no negative number present
if (count_zero == n
|| (count_neg == 0 && count_zero > 0))
return 0;
// If there are all positive
if (count_neg == 0)
return min_pos;
// If there are even number of
// negative numbers and count_neg not 0
if (!(count_neg & 1) && count_neg != 0) {
// Otherwise result is product of
// all non-zeros divided by maximum
// valued negative.
prod = prod / max_neg;
}
return prod;
}
int main()
{
int a[] = { -1, -1, -2, 4, 3 };
int n = sizeof(a) / sizeof(a[0]);
cout << minProductSubset(a, n);
return 0;
}
输出:
-24
时间复杂度: O(n)
辅助空间: O(1)