#include "stdafx.h" //书解法一 int max(int * arr, size_t len) { int * s = new int[len+1]; int * t = new int[len+1]; int * p = new int[len]; s[0] = 1; t[len] = 1; for(int i=1;i<=len;i++) { s[i] = s[i-1] * arr[i-1]; t[len-i] = t[len-i+1] * arr[len-i]; } int max = s[0] * t[1]; for(int i=1;i<len;i++) { p[i] = s[i] * t[i+1]; if(p[i] > max) max = p[i]; } return max; } //书解法二 int max2(int * arr, size_t len) { int t = 1; int nzeros = 0; int max_neg = 0; int min_pos = 0; for(int i=0;i<len;i++) { if(arr[i]==0) nzeros++; else { t*=arr[i]; if(arr[i]<0) { if(max_neg==0 || arr[i]>max_neg) max_neg = arr[i]; } else { if(min_pos==0 || arr[i]<min_pos) min_pos = arr[i]; } } } if(nzeros > 1) return 0; else if(nzeros == 1) { if(t>0) return t; else return 0; } else if(t>0) { return t/min_pos; } else if(t<0) { return t/max_neg; } } int _tmain(int argc, _TCHAR* argv[]) { int arr[5] = {-2,-3,4,-1,6}; printf("%d\n",max(arr,5)); printf("%d\n",max2(arr,5)); return 0; }