最大连续子串问题

具体问题请参考最大连续子串,上班也没什么时间闲睱工夫写了一个答案,也费了近一个多小时间,开始还有错就是在处理0的问题上,后来改正了,算法大致思路是把这个串分成两类来对待0和非0,然后分别处理,最后再从头去掉影响最大乘积的项,生成最终的新的子串,具体代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    //float arr[] = {-2.5,4,0,3,0.5,8,-1,10,-8,0.1,2,4,10,0.01, 200};
	float arr[] = {-2.5,4,0,3,0.5,8,-1,-1, 10};
    //float arr[] = { 0};
    int num = sizeof arr/sizeof(float);
    printf("num = %d\n", num);
    float max = arr[0];
    float cur_max = 1;	    //keep current max value
    float tcur_max = max;   //keep the tmp max value
    int b = 0;              //keep max value frist number
    int tb = 0;	            //keep tmp max value first number
    int e = 0;              //keep max value last number
    int te = 0;             //keep tmp max value last number
    //devide tow parts equal 0 and not equal 0
    int i = 0;
    for(i = 0; i < num; i++)
    {
       if(arr[i] == 0)
       {
           if(max <= tcur_max) //little equal
           {
               max = tcur_max;
               b = tb;
               e = te;
               cur_max = 1;
               tb = i+1;
               te = i+1;
               if(i+1 == num)//a last number
               {
                   tcur_max = cur_max = arr[i];
                   tb --;
                   te --;
               }
           }
           continue;
       }
       cur_max *= arr[i];
       if(tcur_max < cur_max)
       {
           tcur_max = cur_max;
           te = i;
       }
    }
    if(tcur_max > max)
    {
        max = tcur_max;
        b = tb;
        e = te;
    }
	//discard the affect the gene what make max-mutil-value more smaller
    for(i = b; i < e; i++)
    {
        cur_max /= arr[i];
        if(cur_max > max)
        {
            max = cur_max;
            b = i;
        }
    }
    printf("first is arr[%d]=%f, last is arr[%d]=%f, max mutile value is %f\n", b, arr[b],e, arr[e], max);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值