劍指Offer之連續子數組的最大和
- 題目描述:
-
HZ偶爾會拿些專業問題來忽悠那些非計算機專業的同學。今天JOBDU測試組開完會後,他又發話了:在古老的一維模式識別中,常常需要計算連續子向量的最大和,當向量全為正數的時候,問題很好解決。但是,如果向量中包含負數,是否應該包含某個負數,並期望旁邊的正數會彌補它呢?例如:{6,-3,-2,7,-15,1,2,2},連續子向量的最大和為8(從第0個開始,到第3個為止)。你會不會被他忽悠住?
- 輸入:
-
輸入有多組數據,每組測試數據包括兩行。
第一行為一個整數n(0<=n<=100000),當n=0時,輸入結束。接下去的一行包含n個整數(我們保證所有整數屬於[-1000,1000])。
- 輸出:
-
對應每個測試案例,需要輸出3個整數單獨一行,分別表示連續子向量的最大和、該子向量的第一個元素的下標和最後一個元素的下標。若是存在多個子向量,則輸出起始元素下標最小的那個。
- 樣例輸入:
-
3 -1 -3 -2 5 -8 3 2 0 5 8 6 -3 -2 7 -15 1 2 2 0
- 樣例輸出:
-
-1 0 0 10 1 4 8 0 3
【代碼】
/********************************* * 日期:2013-11-21 * 作者:SJF0115 * 題號: 題目1372:連續子數組的最大和 * 來源:https://ac.jobdu.com/problem.php?pid=1372 * 結果:AC * 來源:劍指Offer * 總結: **********************************/ #include<iostream> #include <stdio.h> #include <malloc.h> #include <string.h> using namespace std; int Num[100001]; //連續子數組的最大和 int MaxOfSubArray(int n,int &indexStart,int &indexEnd){ int i,currentMax = 0,num,Max = 0,currentStart = 0; for(i = 0;i < n;i++){ scanf("%d",&num); //初始化 if(i == 0){ currentMax = num; Max = num; indexStart = 0; indexEnd = 0; } else{ //如果當前得到的和是個負數,那麼這個和在接下來的累加中應該拋棄並重新清零, //不然的話這個負數將會減少接下來的和 if(currentMax < 0){ currentMax = 0; currentStart = i; } currentMax += num; //更新最大值 if(currentMax > Max){ Max = currentMax; indexStart = currentStart; indexEnd = i; } } } return Max; } int main() { int n,Max,indexStart,indexEnd; while(scanf("%d",&n) != EOF && n != 0){ Max = MaxOfSubArray(n,indexStart,indexEnd); printf("%d %d %d\n",Max,indexStart,indexEnd); }//while return 0; }
【解法二】
動態規劃
【解析】
【代碼】
/********************************* * 日期:2013-11-21 * 作者:SJF0115 * 題號: 題目1372:連續子數組的最大和 * 來源:https://ac.jobdu.com/problem.php?pid=1372 * 結果:AC * 來源:劍指Offer * 總結: **********************************/ #include<iostream> #include <stdio.h> #include <malloc.h> #include <string.h> using namespace std; //連續子數組的最大和 int MaxOfSubArray(int *array,int n,int &indexStart,int &indexEnd){ int i,Max,currentStart; //初始化 int *current = (int*)malloc(sizeof(int)*n); current[0] = array[0]; Max = array[0]; indexStart = 0; indexEnd = 0; currentStart = 0; //求最大和 for(i = 1;i < n;i++){ if(current[i-1] < 0){ current[i] = array[i]; currentStart = i; } else{ current[i] = array[i] + current[i-1]; } if(current[i] > Max){ Max = current[i]; indexStart = currentStart; indexEnd = i; } } return Max; } int main() { int i,n,Max,indexStart,indexEnd; while(scanf("%d",&n) != EOF && n != 0){ int *array = (int*)malloc(sizeof(int)*n); for(i = 0;i < n;i++){ scanf("%d",&array[i]); } Max = MaxOfSubArray(array,n,indexStart,indexEnd); printf("%d %d %d\n",Max,indexStart,indexEnd); }//while return 0; }
最後更新:2017-04-03 14:54:27