/*
题目:
一个长度为n的数组a[0],a[1],...,a[n-1]。现在更新数组的各个元素,即a[0]变为a[1]到a[n-1]的积,
a[1]变为a[0]和a[2]到a[n-1]的积,...,a[n-1]为a[0]到a[n-2]的积。最后返回更新后数组的最大值。
程序要求:要求1.具有线性复杂度。2.不能使用除法运算符。
解法:更新后a[i] = (a[0]*...*a[i-1]) * (a[i+1]*...*a[n-1]),遍历得到前半部分和后半部分即可。
*/
#include <iostream>
#include <assert.h>
using namespace std;
const int num = 10;
const long init_min = -10000;
long UpdateArray(long *a, int n)
{
long temp = init_min;
long *ptr1 = new long[n];
assert(ptr1 != NULL);
long *ptr2 = new long[n];
assert(ptr2 != NULL);
int i;
ptr1[0] = 1;
ptr2[n-1] = 1;
/*得到(a[0]*...*a[i-1])*/
for(i=1; i<n; i++)
{
ptr1[i] = ptr1[i-1] * a[i-1];
}
/*得到(a[i+1]*...*a[n-1])*/
for(i=n-2; i>=0; i--)
{
ptr2[i] = ptr2[i+1] * a[i+1];
}
for(i=0; i<n; i++)
{
a[i] = ptr1[i] * ptr2[i];
if(a[i] > temp)
{
temp = a[i];
}
}
// cout << *(ptr1+2) << endl;// *ptr equal to ptr[0] equal to *(ptr+0)
delete []ptr1;
delete []ptr2;
return temp;
}
int main()
{
long a[num] = {1,2,3,4,5,6,7,8,9,10};
long MaxItem;
MaxItem = UpdateArray(a, num);
cout << "after updated, the max item is: " << MaxItem << endl;
for(int i=0; i<num; i++)
{
cout << a[i] << " ";
}
cout << endl;
return 0;
}