C – 求整數數組中和最大子串

來源:互聯網
上載者:User

現在有一個數組,數組裡面有正數或者負數。如何計算其子串中和的最大值。
比如{-1,1,2,3,-3},最大值的子串就應該是{1,2,3}值為6

下面我直接給出代碼了,很簡單的,只是當時自己想錯了,所以這裡我把代碼重新寫了一遍:

 1 //時間演算法為o(n^2) 2 int maxseqint(int a[],int n){ 3     int s1, s2; 4     s1=s2=0; 5     for(int i=0;i<n;i++){ 6         s1=0; 7         for(int j=i;j<n;j++){//從s2開始計算其後的資料是否有更大的 8             s1 += a[j]; 9             if(s1 > s2)//如果新算出來的比原來的大10                 s2=s1;11         }12     }13     return s2;14 }15 // 時間複雜度為o(n)16 int maxseqintn(int a[], int n){17     int s1,s2;18     s1=s2=0;19     for(int i=0; i<n;i++){20         s1+=a[i];21         if(s1<0){//因為我們需要求最大值,如果前面是累積和是負數的話,我們就直接取022             s1=0;23         }else if (s1 > s2){24             s2 = s1;25         }26     }27     return s2;28 }29 30 int main()31 {32     int a[] = {-1,1,2,3,-3};33     int s = maxseqintn(a,5);34     printf("max seq int:%d",s);35 }

寫完了。謝謝

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.