方法一
使用动态规划逐步求解
int *s = new int[n+1];
int *t = new int[n+1];
int *p = new int[n+1];
s[0] = 1;
// s[i]表示前i个元素的乘积
t[n] = 1;
// t[i]表示后n-i个元素的乘积, p[i]表示除第i个元素之外其他N-1个元素的乘积
for (int i = 1; i <= n; i++) {
s[i] = s[i-1]*a[i-1];
}
for (int i = n; i >= 1; i--) {
t[i-1] = t[i]*a[i-1];
}
for (int i = 1; i < n; i++) {
p[i] = s[i-1]*t[i];
}
int max_index = 1;
for (int i = 1; i < n; i++) {
if (p[max_index] < p[i])
max_index = i;
}
cout << "最大值为除去a[" << max_index << "]外的元素" << endl;
return p[max_index];
cout << max_product(a, 10) << endl;
return 0;
int positive_num = 0;
int min_positive = INT_MAX;
int negative_num = 0;
int max_negative = INT_MIN;
int zero_num = 0;
for (int i = 0; i < n; i++) {
if (a[i] > 0) {
++positive_num;
if (a[i] < min_positive)
min_positive = a[i];
} else if (a[i] < 0) {
++negative_num;
if (a[i] > max_negative)
max_negative = a[i];
} else {
zero_num++;
}
++positive_num;
if (a[i] < min_positive)
min_positive = a[i];
} else if (a[i] < 0) {
++negative_num;
if (a[i] > max_negative)
max_negative = a[i];
} else {
zero_num++;
}
int negative_num = 0;
int max_negative = INT_MIN;
int zero_num = 0;
for (int i = 0; i < n; i++) {
if (a[i] > 0) {
++positive_num;
if (a[i] < min_positive)
min_positive = a[i];
} else if (a[i] < 0) {
++negative_num;
if (a[i] > max_negative)
max_negative = a[i];
} else {
++zero_num;
}
}
if (zero_num > 1) {
cout << "不管去掉哪个数结果都是0" << endl;
} else if (zero_num == 1) {
if (negative_num%2 == 0) {
// 有偶数个负数
cout << "去掉0" << endl;
} else {
//有奇数个负数,去掉绝对值最小的负数
cout << "去掉" << max_negative << endl;
}
} else {
if (negative_num%2 == 0) {
// 有偶数个负数,去掉绝对值最小的正数
cout << "去掉" << min_positive << endl;
} else {
//有奇数个负数,去掉绝对值最小的负数
cout << "去掉" << max_negative << endl;
}
}
int a[5] = {1, 2, 3, 4, -6};
max_product(a, 5);
return 0;
#include
using namespace std;
int max_product(int a[], int n) {
}
int main() {
int a[10] = {1, 2, 3, -4, -6, 5, -8, 4, -2, -1};
}
方法二
根据正数负数和0的个数
#include
#include
using namespace std;
void max_product(int a[], int n) {
}
int main() {
}