01-复杂度2. 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
<pre name="code" class="plain">#include<stdio.h>
int main()
{
int k,k0,cnt=0;
scanf("%d",&k);
k0=k;
int head=0,end=0;
int First=0,first=0,Last=0,last=0;
int thismax=0,max=0,temp=0;
while(k){
scanf("%d",&temp);
--k;
//处理纯负数
if(temp<0&&max==0){
if(cnt==0){
head=temp;
}
else{
end=temp;
};
++cnt;
};
//主体
if(thismax==0&&k==k0-1&&temp>0) First=first=temp; //初始化子列首数据
if(thismax>=0) //注意等于零时也可以
{
thismax+=temp;
last=temp;
}
else{ //如果子列和已经为负,则舍弃,重新开始
thismax=temp;
first=temp;
last=temp;
};
if(thismax>max){ //发现新的最大值,则更新数据
max=thismax;
Last=last;
First=first;
};
}
if(cnt==k0){
printf("%d %d %d\n",max,head,end);
}else
printf("%d %d %d\n",max,First,Last);
return 0;
}
该算法不受数据大小10000的限制,但是这个算法对纯负数数组的处理不大有效率,每次都要判断。在网上找的另一个算法,不是即时算法,而是采用了数组,这样的话,空间复杂度较高:
#include <stdio.h>
int a[10001];
int main(){
int k;
int i;
scanf("%d", &k);
for (i = 0; i < k; i++){
scanf("%d", &a[i]);
}
int sum = 0, start = 0, end = k - 1, temp = 0, tempi = 0, tempj = 0;
for (i = 0; i < k; i++){
if (temp >= 0){
temp += a[i];
tempj = i;
}
else{
temp = a[i];
tempi = i;
tempj = i;
}
if (temp > sum || (temp == 0 && end == k -1)){
sum = temp;
start = tempi;
end = tempj;
}
}
printf("%d %d %d\n", sum, a[start], a[end]);
return 0;
}
PAT评判准则的几个临界或特殊情况:
1.全负数数组,给出首尾数字;
2.同时有几个最大和子列,取最先得到的;
①最大和子列后跟着零不计,实质就是情况2;
②最大和子列,若跟在一个 和为零 的子列后面,则应该将这个和为零的子列也算入最大和子列中。