最大子段和(動態規劃)

給出N個數字, 計算出最大的子段和。

Input

第一行給出一個數字 T(1<=T<=20) 代表接下來的組數. 
接下來每 T 行,開始給出一個數組 N(1<=N<=100000), 接着跟着N個數字.

數據保證最後結果小於2^31.

Output

輸出最大的字段和

 

Sample Input
2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
 

Sample Output
14
7


思路:加入最長子段和是 ai ,ai+1 ,.....aj-1,aj

那麼,ai前面加起來都是小於0的,aj後面的加起來也都是小於0的


#include<iostream>
#define MAX 100001
void vInput(int nArray[],int nNum);
int nGetResult(int nArray[],int nNum);
void vOutput(int nResult);

int main(){
 int nCase;
 int nNum;
 int i;
 int nArray[MAX];
 int nResult;

 while(1==scanf("%d",&nCase)){
  for(i=1;i<=nCase;i++){
   scanf("%d",&nNum);
   vInput(nArray,nNum);
   nResult=nGetResult(nArray,nNum);
   vOutput(nResult);
  }
 }
 return 0;
}

void vInput(int nArray[],int nNum){
 int i;
 for(i=1;i<=nNum;i++){
  scanf("%d",&nArray[i]);
 }
}
int nGetResult(int nArray[],int nNum){
 int i;
 int nSum=0;
 int nTempSum=0;
 for(i=1;i<=nNum;i++){
  if(nTempSum>=0){
   nTempSum+=nArray[i];
   if(nSum<nTempSum){
    nSum=nTempSum;
   }
  }else{
   nTempSum=nArray[i];
  }
 }
 return nSum;
}
void vOutput(int nResult){
 printf("%d\n",nResult);
}


發佈了44 篇原創文章 · 獲贊 12 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章