[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, givebaa1
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; }
相关文章推荐
- [PTA刷题]Maximum Subsequence Sum
- PAT1007 Maximum Subsequence Sum (25)
- PTA_01-复杂度2 Maximum Subsequence Sum
- 01-复杂度2 Maximum Subsequence Sum(25 分)
- 1007. Maximum Subsequence Sum (25)
- PAT Maximum Subsequence Sum (25)
- Maximum Subsequence Sum (25)
- Maximum Subsequence Sum[PAT1007][PTA01-复杂度2]——动态规划
- PAT Maximum Subsequence Sum (25)
- 01-复杂度2 Maximum Subsequence Sum(25 分)
- 1007 Maximum Subsequence Sum (25)
- PAT (Advanced Level) Practise 1007 Maximum Subsequence Sum (25)
- 01-复杂度2 Maximum Subsequence Sum(25 分)
- dyx-- Maximum Subsequence Sum (25)
- 【PAT】1007 Maximum Subsequence Sum (25) 最大连续子序列和 +记录位置
- 01-复杂度2 Maximum Subsequence Sum(25 分)
- Maximum Subsequence Sum浙大数据结构
- 浙大数据结构 Maximum Subsequence Sum (C++实现)
- 中国大学MOOC-陈越、何钦铭-数据结构 Maximum Subsequence Sum
- PATA-1007 Maximum Subsequence Sum (25)