《数学之美》2.13的一道题:
给定一个长度为N的整数数组,只允许用乘法,不能用除法,计算任意(N-1)个数的组合乘积中最大的一组,并写出算法的时间复杂度。
最容易想到的办法是:把所有可能的(N-1)个数的组合找出来,分别计算它们的乘积,并比较大小。由于总共有N个(N-1)个数的组合,总的时间复杂度为O(N*N),但显然这不是最好的解法。
假如去掉的元素是a[i],先计算a[0]...a[i-1]的乘积,再计算a[i+1]...a[N-1]的乘积再相乘即可,为了避免重复的计算乘积,可以先遍历一遍数组求得前i个元素的乘积存入p数组,即:p[i]=Multiply(a[0]...a[i-1])(其中1 <= i <= N,特别的p[0]为1);再遍历一遍数组求得后N-i个元素的乘积存入q数组,即:q[i]=Multiply(a[i]...a[N-1])(其中0 <= i
#include
#include
using namespace std;
int MaxProduct(int *arr, size_t len)
{
assert((arr != NULL) && (len > 0));
int *p = new int[len + 1];
int *q = new int[len + 1];
//p[i] records the multiply product of arr[0] to arr[i-1],
//exceptionally, p[0]=1
p[0] = 1;
for (int i = 1; i <= len; i++)
{
p[i] = p[i-1] * arr[i-1];
}
//q[i] records the multiply product of arr[i] to arr[len-1],
//exceptionally, p[len]=1
q[len] = 1;
for (int i = len-1; i >= 0; i--)
{
q[i] = q[i+1] * arr[i];
}
int maxRes = 0x80000000;
for (int i = 0; i < len; i++)
{
int nTemp = p[i] * q[i+1];
if (nTemp > maxRes)
{
maxRes = nTemp;
}
}
return maxRes;
}
int main()
{
int arr[6] = {1, 4, -2, 5, -3, 3};
int res = MaxProduct(arr, 6);
cout << "max product : " << res << endl;
return 0;
}
该方法对数组中出现的数和乘积的规律进行了分析,该方法总共只需遍历数组两次,第一次遍历完数组后某些情况可以提前结束,例如数组中0的数目大于1,则结果直接为0,因此该方法效率比方法二要高。原理很简单,不再具体赘述,可以参考《数学之美》中的叙述。代码如下:
#include
#include
using namespace std;
int MaxProduct(int *arr, size_t len)
{
assert((arr != NULL) && (len > 0));
size_t cntZero = 0; //count of zeros
size_t cntNega = 0; //count of negatives
size_t idxMinPosi = 0; //index of min positive value
size_t idxMaxNega = 0; //index of max negative value
size_t idxZero = 0; //index of the only zero
int minPosi = arr[0];
int maxNega = 0x80000000;
for (int i=0; i 0)
{
if (arr[i] < minPosi)
{
minPosi = arr[i];
idxMinPosi = i;
}
}
else
{
++cntNega;
if (arr[i] > maxNega)
{
maxNega = arr[i];
idxMaxNega = i;
}
}
}
size_t nExcepPos = 0; //the pos of exception number
if (cntZero > 1) //more than 1 zero
{
return 0;
}
else if (cntZero == 1) // 1 zero
{
if (cntNega % 2)
{
return 0;
}
else
{
nExcepPos = idxZero;
}
}
else //no zero
{
if (cntNega % 2)
{
nExcepPos = idxMaxNega;
}
else
{
nExcepPos = idxMinPosi;
}
}
int maxRes = 1;
for (int i=0; i