給定一串數字求連續的最大和

來源:互聯網
上載者:User

題目描述:有31,-41,59,26,-53,58,97,-93,-23,84十個數。SUM(N,M)表示從第N個數到到第M個數的和。例如:SUM(2,3)=-41+59=18。問:最大的和是多少?對應的N和M是多少?

演算法思想:數組中的數字可以看做用負數分割開的一段一段正數,先找出這幾段正數中和最大的那段(這題的結果的那串數字必定包括和最大的那串正數)然後慢慢的向兩邊擴散。文字功底不是很好 不太會描述 大家看程式注釋吧(該演算法有個缺陷 就是當有幾串聯續正數的和相同時無法處理 不過對於現在這個題目給定的資料中不存在這種情況 但是如果讓使用者自己輸入的話....所以大家有什麼好的解決方案或者其他好的演算法 麻煩請給我留言)

#include <stdio.h>#define MAXN10int main(void){int a[10] = {31, -41, 59, 26, -53, 58, 97, -93, -23, 84};int positive[MAXN];int i, j, k;int flag;int max, temp;int left, right;i = j = 0;while (a[i] < 0)//該迴圈從左側開始找第一個非負數  i記錄其下標 ++i;max = 0;temp = 0;//該迴圈找到整個數組中和最大的連續正數 //並用left和right分別記錄該段連續正數最左邊和最右邊兩個正數的下標 for (k=0; i<10; ++i) {if (a[i] >= 0) {j = i;while (a[i] >= 0 && i < 10)temp += a[i++];if (temp > max) {left = j;right = i-1;max = temp;}positive[k++] = temp;temp = 0;}}flag = 0;temp = 0;for (i=left-1; i>=0; --i) {if (a[i]<0 && !flag) {  //向左邊擴散 先把連續的n個負數加起來 temp += a[i];} else {//碰到了第一個正數 flag = 1; if (a[i]>=0 && flag) {//把碰到的連續幾個正數加起來temp += a[i];} else if (a[i]<0 && flag) {//又碰到了一個負數 if (temp >= 0) {//收益為正數 可以加上 left = i+1; max += temp;temp = 0; ++i;flag = 0;continue;} else {//收益為負數 結束迴圈 break;}} }}//printf("%d  %d  %d\n", left, right, max);flag = 0;temp = 0;for (j=right+1; j<10; ++j) {if (a[j]<0 && !flag) {temp += a[j];} else {flag = 1;if (a[j]>=0 && flag) {temp += a[j];} else if (a[j]<0 && flag) {if (temp >= 0) {right = j-1; max += temp;temp = 0;--j;flag = 0;continue;} else {break;}}}}printf("N = %d  M = %d  SUM = %d\n", left, right, 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.