具體問題請參考最大連續子串,上班也沒什麼時間閑睱工夫寫了一個答案,也費了近一個多小時間,開始還有錯就是在處理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;}