首页 > 代码库 > Max Sum

Max Sum

 

Max Sum

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 157635    Accepted Submission(s): 36871


Problem Description
Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
 

Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
 

Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
 

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

Sample Output
Case 1: 14 1 4 Case 2: 7 1 6
 

Author
Ignatius.L
 

 要注意最大值值可能是负数 , so 不要用 result = 0 去比较取最大值 ;

看看能不能过 2 -7 7 这组。

(一开始我写的代码只能保证 在首项  非负是成立 ,so WA )

技术分享
 1 #include<stdio.h> 2 #include<string.h> 3 int N ; 4 int a[100001] ; 5 int dp[100001] ; 6  7 int main() 8 { 9     freopen ( "a.txt" ,"r" , stdin ) ;10     int T;11     int i , j ;12     int cnt = 0 ;13     int start , end ;14     int result ;15     scanf ( "%d" , &T ) ;16     while ( T-- )17     {18         scanf ( "%d" , &N );19         memset ( dp , 0 , sizeof(dp) );20         for ( i = 1 ; i <= N ; i++ )21             scanf ( "%d" , &a[i] ) ;22 23         for ( i = 1 ; i <= N ; i++ )24         {25                 if ( dp[i - 1] + a[i] >= 0 && dp[i - 1] >= 0)26                     dp[i] = dp[i - 1] + a[i] ;27                 else28                 {29                     dp[i] = a[i] ;30                 }31         }32         result = 1 ;33         for ( i = 2 ; i <= N ; i++ )34         {35             if( dp[result] < dp[i] )36                 result = i ;37         }38         start = dp[result] ;39         for ( j = result ; j >= 1 ; j-- )40         {41             start-= a[j] ;42             if ( !start )43                 end = j;44         }45         printf ( "Case %d:\n%d %d %d\n" , cnt + 1 , dp[result] , end , result ) ;46         cnt++ ;47         if ( T )48             printf ( "\n" ) ;49     }50     return 0;51 }
dp

 

Max Sum