求最大和

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

 
思路分析:
            在输入的同时就一边计算。
            把当前输入的值都计算出来now+bef,再与刚刚输入进去的值比较now。如果now大,就把bef更新。并且记录此时的计算位置。
            每次bef与max比较,直到找出最大值。
           /(ㄒoㄒ)/~~终究摆脱不了百度,看别人博客。。。。
 
源代码:
 1 #include<iostream>
 2 using namespace std;
 3 int main()
 4 {
 5     int T, icase = 0, max, n, bef, now, s, e, k;
 6     cin >> T;
 7     while (T--)
 8     {
 9         
10         icase++;
11         cin >> n;
12         for (int i = 1; i <=n; i++)
13         {
14             cin >> now;
15             if (i == 1)
16             {
17                 max=bef =now ;
18                 k = s = e = 1;        //初始化ing……
19             }
20             else
21             {
22                 if (now > bef + now)//当前值大于之前的和
23                 {
24                   bef = now;     //把当前的值作为最新的值
25                     k = i;         //记录更新的开始位置
26                 }
27                 else
28                     bef+=now;   //计算总和
29             }
30             if (bef > max)         //当前值大于了之前计算的最大值,max一直等于now
31                 max = bef, s = k, e = i;
32         }
33         
34         cout << "Case " << icase << ":
"<< max << " " << s << " " << e << endl;
35         if (T)
36             cout << endl;
37     }
38     return 0;
39 }
 
心得:
 
 
              加油加油加油↖(^ω^)↗干吧得!
原文地址:https://www.cnblogs.com/Lynn0814/p/4718490.html