Programe_Of_Beauty:2.13 子数组的最大乘积
2011-06-12 00:07 x_feng 阅读(218) 评论(1) 收藏 举报问题:给定一个长度为N的整数数组,只允许用乘法,不用除法,计算任意N-1个数的组合中乘积最大的一组。具体思想不再赘述,代码如下:
#ifndef _SUB_ARRAY_MAX_MULTIPLY_H_
#define _SUB_ARRAY_MAX_MULTIPLY_H_
#include <iostream>
using namespace std;
//方法一
void SubArryMaxMultiply_Calculate(int* array, int size)
{
if (NULL == array)
{
return;
}
int* a = new int[size];
int* b = new int[size];
memset(a, 1, sizeof(int)*size);
memset(b, 1, sizeof(int)*size);
a[0] = array[0];
b[size - 1] = array[size - 1];
for (int i = 1, j = size - 2; i < size; i++, j--)
{
a[i] = a[i - 1]*array[i];
b[j] = b[j + 1]*array[j];
}
int temp = -217345;
for (i = 0; i < size ; i++)
{
if (i ==0)
{
if (b[i+i] > temp)
{
temp = b[i+1];
}
}
else if (i == size - 1)
{
if (a[size - 2] > temp)
{
temp = a[size -2];
}
}
else
{
if (a[i-1]*b[i+1] > temp)
{
temp = a[i-1]*b[i+1];
}
}
}
cout<<"max multiply="<<temp<<endl;
delete []a;
delete []b;
}
//方法二
void SubArryMaxMultiply_Judge(int* array, int size)
{
int negativeCount = 0;//记录负数个数
int zeroCount = 0;//记录0的个数
int absoluteMinNegativeData = 217456;//记录绝对值最小负数
int absoluteMaxNegativeData = 0;//记录绝对值最大负数
int absoluteMinPlusData = 217456;//记录最小正数
for (int i = 0; i < size; ++i)
{
if (array[i] == 0)
{
zeroCount++;
}
else if (array[i] < 0)
{
negativeCount++;
if (abs(array[i]) < abs(absoluteMinNegativeData))
{
absoluteMinNegativeData = array[i];
}
if (abs(absoluteMaxNegativeData) < abs(array[i]))
{
absoluteMaxNegativeData = array[i];
}
}
else
{
if (array[i] < absoluteMinPlusData)
{
absoluteMinPlusData = array[i];
}
}
}
if (zeroCount > 1)
{
cout<<"max multiply="<<"0"<<endl;
return;
}
else if (zeroCount == 1)
{
cout<<"remove 0"<<endl;
return;
}
else
{
if (negativeCount%2 == 1)
{
cout<<"remove "<<absoluteMinNegativeData<<endl;
return;
}
else
{
if (negativeCount == size)
{
cout<<"remove "<<absoluteMaxNegativeData<<endl;
return;
}
cout<<"remove "<<absoluteMinPlusData<<endl;
return;
}
}
}
#endif
浙公网安备 33010602011771号