Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 372365 Accepted Submission(s): 89255
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.
题意分析
求最大子序列,序列是连续的,且一般负数不作为首项
注意这题数组要开大一点,而且要注意时间复杂度不能太高,所以两个for 的都可以劝退了,
注意一开始的比较要不-1000还要小,不然就wa了,空行的处理也要注意,具体看我ac代码。
写了两节java课才写完的,细节方面没处理好卡了很长时间。
AC代码
#include<iostream>
using namespace std;
int arr[100010];
int main() {
int n, a, x1, x2, count = 1;
scanf("%d", &n);
while (n--) {
scanf("%d", &a);
for (int j = 0; j < a; j++) {
scanf("%d", &arr[j]);
}
int max = -2000, sum = 0, x = 0;
for (int m = 0; m < a; m++) {
sum += arr[m];
if (max < sum) {
max = sum;
x1 = x, x2 = m;
}
if (sum < 0) {
sum = 0;
x = m + 1;//这里是要注意的,一开始我就是这写错了,搞了很久
}
}
printf("Case %d:\n%d %d %d\n", count ++, max, x1 + 1, x2 + 1);
if (n != 0) {
printf("\n");
}
}
}