您的位置:首页 > 产品设计 > UI/UE

[PTA MOOC] Maximum Subsequence Sum(25 分)(也是浙大研究生机试的题)

2017-09-01 23:07 288 查看

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, give
baa1
n 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≤100000. 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 -21


Sample Output:

10 1 4


注意点:

全是负数

有负数有0

注意到不管怎么样后面的index都是可以掌握的

#include <stdio.h>
#define MAX 100000
int num[MAX]={0,0,0};

//flag为了判断是否全是负数
int main() {
int k, a, flag=0;
scanf("%d", &k);
for(int i=0; i<k; ++i) {
scanf("%d", &a);
num[i] = a;
}
int maxSum=num[0], thisSum=0, indexI=0, indexJ=0;
for(int i=0; i<k; ++i) {
thisSum += num[i];
if(num[i]>=0) flag=1;
if(thisSum > maxSum) {
maxSum = thisSum;
indexJ = i;
//我只判断最后一个的位置
}
else if(thisSum<0) {
thisSum = 0;
}
}
int temp = maxSum;
//确定开头的位置,注意如果前面是0还要继续,也就是说没有break
for(int i=indexJ; i>=0; --i) {
temp -= num[i];
if(!temp) {
indexI = i;
}
}

if(!flag) {
maxSum = 0;
indexI = 0;
indexJ = k-1;
}
printf("%d %d %d", maxSum, num[indexI], num[indexJ]);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c