PAT甲级1007 Maximum Subsequence Sum (25分) [最大子串和,在线处理]题解

tech2022-11-22  92

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 -21

Sample Output:

10 1 4

题目大意

给定一个字符串,要求你求出他的最大子串和,即在字符串的所有子串中,找出和最大的子串。

题目分析

用一个int型的数组存储数据,首先输入为一个正整数N,表明字符串中一共有N个数字,设计利用一个int型的数组存储字符串。这道题算法利用在线处理,从前往后数。每读入一个数字就进行判断,如果当前的求和结果大于零,保留;如果大于零且大于之前计算的最大值,对最大值,左右边界的值进行替换;如果小于零说明当前串的值对后续串的值的影响为减小后续子串的值,舍去当前串,重新从零开始计算,将左边界置为舍去子串后一个数字。

代码

#include "stdio.h" int main(){ int N; int maxsum,thissum; int leftindex,rightindex; int a[10005]; int i; int flag; scanf("%d",&N); for (i = 0;i < N;i++){ scanf("%d",&a[i]); }//输入字符串,存储中a数组中。 flag = 0; maxsum =-1; thissum = 0; leftindex = 0; rightindex= N-1; for (i = 0;i < N;i++) {//遍历字符串 thissum += a[i]; if (thissum < 0){ thissum = 0; flag = i + 1; }//如果当前串的和小于零,说明他对后续串的相加结果一定是让后续结果变小,所以舍去这一部分,将flag换为当前之后的起点。 else if (thissum > maxsum ){ leftindex = flag; rightindex =i; maxsum = thissum; }//如果子串变大且大于之前已经得到的最大值,将最大值,左右边界都进行替换。 } if (maxsum < 0) maxsum = 0; printf("%d %d %d",maxsum,a[leftindex],a[rightindex]); }
最新回复(0)