最大子串乘积

最大子串乘积

                 输入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.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值