Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 194228 Accepted Submission(s): 45313
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
Recommend
We have carefully selected several similar problems for you: 1176 1087 1069 2084 1058
中心思想:先知道求最大子数组和的思想也就是设以i为结尾最大子数组和,那么它一定是由i-1为尾加上arr[i]或者arr[i]本身二者中最大值(从新开始寻找最大子数组,从i开始,前面的废弃)。
那么就是看i-1结尾是不是大于0。
然后就是用2个变量确定变换的时候的首尾,一旦有变换,就立即改变,最后输出
#include<iostream>
using namespace std;
int arr[100002];
int start[100002];
int main(){
int T;
cin >> T;
int num = 1;
while (T--)
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> arr[i];
}
int currsum = arr[1];
int maxsum = arr[1];
start[1] = 1; int end = 1;
for (int i = 2; i <= n; i++)
{
if (currsum >= 0){
currsum += arr[i];
start[i] = start[i - 1];
}
else
{
currsum = arr[i];
start[i] = i;
}
if (currsum >= maxsum)
{
maxsum = currsum;
end = i;
}
}
printf("Case %d:\n", num);
num++;
printf("%d %d %d\n", maxsum, start[end], end);
if (T)
printf("\n");
}
}