/************************** *程序员:刘晋勋 *日期:2010/04/21 *功能:求子数组的最大乘积 *目的:编程练习 **************************/ #include<stdio.h> #include<stdlib.h> #include<string.h> long MaxProOfSubArray(int arr[],int size) { long res = 0;//最大子数组乘积初始化 //s[i]表示前i个元素的乘积,那么s[i] = s[i-1]*arr[i-1](1<=i<=N) long *s = (long*)malloc(sizeof(int)*size); memset(s,0,sizeof(int)*size); s[0] = 1; //t[i]表示后(N-i)个元素的乘积,那么t[i]=t[i+1]*arr[i](1<=i<=N) long *t = (long*)malloc(sizeof(int)*size); memset(t,0,sizeof(int)*size); t[size] = 1; //设p[i]为除第i个元素之外的其他元素之积,即:p[i]=s[i-1]*t[i+1]; long *p = (long*)malloc(sizeof(int)*(size+1)); memset(p,0,sizeof(int)*(size+1)); //求出 s数组 for (int i = 1; i <= size; i++) { s[i] = s[i-1]*arr[i-1]; } //求出t数组 for (int j = size - 1;j >= 0; j--) { t[j] = t[j+1]*arr[j]; } // 计算 p数组 for (int k = 1; k <= size; k++) { p[k] = s[k - 1] * t[k]; if (p[k] > res) { res = p[k]; } } return res; } int main() { int A[]={1,4,6,10,12,40}; long max = MaxProOfSubArray(A,6); printf("%ld",max); return 0; }