最大子串乘积
输入n个数,求它的最大的连续子串乘积。
例:
输入
7
1 2 -3 7 0 2 3
输出
7
代码实现:
#include <stdio.h>
int Max_Subsegment(int * Arr , int len)///-----最大子段乘积函数
{
int i , j;
int temp = 1;
int sum = 1;
int max = Arr[0];
for(i = 0 ; i < len ; i++){///---本程序的双重循环是为了:
/// 保证含有多个负数的时候也能得到正确答案;
///---例:第一组测试数据
/// 无负数的话可以去掉一重循环,并改进(去掉L19--25)
temp = sum = 1;
for(j = i ; j < len ; j++){
temp *= Arr[j];
max = temp > max ? temp : max;
if( Arr[j] == 0){
temp = sum = 1;
}
else if( Arr[j] > 0 ){
sum *= Arr[j];
max = sum > max ? sum : max;
}
else {
sum = 1;
}
}
}
return max;
}
int main()///-----------main()
{
int m;
while((scanf("%d",&m)) !=EOF ,m > 0){/// --- 多组输入
int i;
int Arr[m];///----动态数组
for(i = 0 ; i < m ; i++){
scanf("%d",&Arr[i]);
}
printf("%d\n",Max_Subsegment(&Arr[0] , m));
printf("---------end--------\n\n");
}
return 0;
}
案例:
6
1 2 -3 -4 6 -7
168
---------end--------
5
1 2 -3 4 6
24
---------end--------
7
1 2 -3 7 0 2 3
7
---------end--------
8
1 2 3 4 -5 6 7 4
168
---------end--------
5
0 0 0 0 0
0
---------end--------
0
Process returned 0 (0x0) execution time : 128.646 s
Press any key to continue.