1007. Maximum Subsequence Sum (25)
Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to be { Ni, Ni+1, ..., Nj } where 1 <= i <= j <= K. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.
Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.
Input Specification:
Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (<= 10000). The second line contains K numbers, separated by a space.
Output Specification:
For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.
Sample Input:10 -10 1 2 3 4 -5 -23 3 7 -21Sample Output:
10 1 4
最开始自己的代码过不了第三个测试点和最后一个测试点,三个for循环的嵌套时间复杂度太高n3,后来参考了网上的另一种解法直接降到线性复杂度#include<stdio.h> #include<stdlib.h> int main() { int max; int begin; int end; int sum; int x,a,n; scanf("%d", &n); scanf("%d", &a); sum = a; max = a; begin = end = a; int s = a; x = a; for (int i = 2; i <= n; i++) { scanf("%d", &a); if (sum >= 0) sum += a; else { sum = a; x = a; } if (max<sum) { max = sum; begin = x; end = a; } } if (max < 0) printf("0 %d %d", s, a); else printf("%d %d %d", max, begin, end); return 0; }
#include<stdio.h> #include<stdlib.h> int main() { int N; int sum = 0, ini = 0, end = 0,max=0; int i, j, k; scanf( "%d", &N); int* data = (int*)malloc(sizeof(int)*N); for (i = 0; i < N; i++) scanf( "%d", &data[i]); for (i = 0; i < N; i++) { for (j = i; j < N; j++) { sum = 0; for (k = i; k <= j; k++) sum = sum + data[k]; if (sum > max) { max = sum; ini = data[i]; end = data[j]; } else if (sum == max) { if (i < ini) { ini = data[i]; end = data[j]; } else if (i == ini&&j < end) { ini = data[i]; end = data[j]; } } } } for (i = 0; i < N; i++) if (data[i] >= 0)break; if (i == N) { sum=0; ini=data[0]; end=data[N-1]; } printf("%d %d %d", max, ini, end); return 0; }