具体问题请参考最大连续子串,上班也没什么时间闲睱工夫写了一个答案,也费了近一个多小时间,开始还有错就是在处理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;
}