最大連續子串問題

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.