Maximum Subsequence Sum
Given a sequence of K integers { , , ..., }. A continuous subsequence is defined to be { , , ..., } where . 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 (). The second line contains 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 and (as shown by the sample case). If all the 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 -21
Sample Output:
10 1 4
I wrote a program like this:
//Maximum Subsequence Sum
#include <stdio.h>
int maxSum(int a[], int K, int &first);
int main(void)
{
int K, i, first = 0, max, sum = 0;
scanf("%d", &K);
if (K>=1&&K<=100000)
{
int a[100000];
for(i=0;i<K;i++)
scanf("%d",&a[i]);
max = maxSum(a, K, first);
if (max>0)
{
for(i=first;sum!=max;i++)
sum += a[i];
}
else if (a[first] == 0)
++i;
else
i = K;
printf("%d %d %d\n",max,a[first],a[i-1]);
return 0;
}
}
int maxSum(int a[], int K, int &first)
{
int i;
int ThisSum = 0;
int MaxSum = 0;
for(i=K-1;i>=0;--i)
{
ThisSum += a[i];
if (ThisSum>=MaxSum)
{
MaxSum = ThisSum;
first = i;
}
else if (ThisSum<0)
{
ThisSum = 0;
}
}
return MaxSum;
}
Acturally, I've tried to transform this C program into Java program with the same algorithm, but failed to pass the Online Judge, due to the poor time efficiency of Java compared to C language. Do you hava a good idea? Relative limits are following.
Time Limit: 200ms
Memory limit: 64MB
Code length restriction: 16kB
Expecting your better methods.
No comments:
Post a Comment