1888. Circular Sequence
Constraints
Time Limit: 1 secs, Memory Limit: 32 MB
Description
Given a sequence with n elements, if the last element is also adjacent to the first element of the sequence, the sequence is called “circular sequence”.
Now, here comes a simple problem: given a circular sequence, you should find a segment of the sequence, such that it contains at least one element, and the sum of the elements is as large as possible.
Input
Input may contain several test cases. The first line is a single integer t, the number of test cases below. Each test case is composed of two lines. The first line of each test case is a positive integer n (1<=n<=100000), denoting the number of elements in the circular sequence, and the second line has n integers; the absolute value of each integer is no more than 100000.
Output
For each test case, output the maximum segment sum in a single line.
Sample Input
2 2 -1 -2 3 1 -2 3
Sample Output
-1 4
非常好的一道题
在这里贴上大神的作品:http://www.ahathinking.com/archives/120.html
OK:上代码,两个时间都是0.27s:
#include <stdio.h> #define INF -99999999 int a[100005]; long long max(int n) { long long sum = 0; long long max = INF; for (int i = 0; i < n; i++) { if (sum < 0) { sum = a[i]; } else { sum += a[i]; } if (sum > max) { max = sum; } } return max; } long long min(int n) { long long sum = 0; long long min = -INF; for (int i = 0; i < n; i++) { if (sum > 0) { sum = a[i]; } else { sum += a[i]; } if (sum < min) { min = sum; } } return min; } long long sum_all(int n) { long long sum = 0; for (int i = 0; i < n; i++) { sum += a[i]; } return sum; } int main() { int n, case_num, i; long long temp1, temp2; scanf("%d", &case_num); while (case_num--) { scanf("%d", &n); for (i = 0; i < n; i++) { scanf("%lld", &a[i]); } temp1 = max(n); temp2 = sum_all(n) - min(n); if (temp1 < 0) printf("%lld\n", temp1); else printf("%lld\n", temp1 > temp2 ? temp1 : temp2); } return 0; }
这个时间相同,当时看起来会精简点:
#include <stdio.h> #define INF -99999999 int a[100005]; long long ans(int n) { long long sum_all = 0, sum_min = 0, sum_max = 0, max = INF, min = -INF; for (int i = 0; i < n; i++) { if (sum_max < 0) { sum_max = a[i]; } else { sum_max += a[i]; } if (sum_max > max) max = sum_max; if (sum_min > 0) { sum_min = a[i]; } else { sum_min += a[i]; } if (sum_min < min) { min = sum_min; } sum_all += a[i]; } if (max < 0) { return max; } else { return max > sum_all - min ? max : sum_all - min; } } int main() { int n, case_num, i; scanf("%d", &case_num); while (case_num--) { scanf("%d", &n); for (i = 0; i < n; i++) { scanf("%lld", &a[i]); } printf("%lld\n", ans(n)); } return 0; }