Maximum Subsequence Sum

Maximum Subsequence Sum

Given a sequence of K integers { N​1​​, N​2​​, …, N​K​​ }. A continuous subsequence is defined to be { N​i​​, N​i+1​​, …, N​j​​ } 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


分析:
最大子列和问题的加强版,2004年浙江大学计算机专业考研复试真题。

翻译过来就是求一个序列的最大子列和,并输出最大子列和的开头和结尾的数,求最大子列和我们可以累加当前序列,如果序列和小于 0 就置 0 重新累加,否则更新最大值。

现在的问题是如何记录开头和结尾的数
结尾的数,就是每次更新最大值时记录当时的序号,该序号对应的值就是结尾的数。
而开头的数和每次序列和小于 0 相关,每次序列和清零时表示抛弃了这段子序列,之后有新的开始,所以清 0 后下一个序列号里存的就是子序列开头的数,那么如何记录下这个数?对了,更新最大值的时候!每次更新最大值相当于固定一段子序列。

最后一个问题就是,当只有一个 0,其余全为负数的情况,按道理应该输出全 0,但是实际输出的是 “0 第一个数 最后一个数”,为了避免这种情况,我们将最大值初值赋为 -1,这样遇到 0 时也能更新最大值。

Java代码:

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int K = scanner.nextInt();
		int[] a = new int[K];
		for (int i = 0; i < a.length; i++) {
			a[i] = scanner.nextInt();
		}
				
		MaxSubsequenceSum(a);
	}

	private static void MaxSubsequenceSum(int[] a) {
		int ThisSum = 0,MaxSum = -1;			//保存序列的临时和以及最大和,MaxSum初始值定为-1,是为了应对序列中只有负数和零的情况
		int left = 0,right = 0,t = 0;			//保存连续序列的首、末元素位置,t记录临时首位置
		for (int i = 0; i < a.length; i++) {
			ThisSum += a[i];
			
			if (ThisSum > MaxSum) {
				MaxSum = ThisSum;				//发现更大和则更新当前结果
				left = t;
				right = i;						//更新连续序列的末元素位置为当前位置
			}
			if (ThisSum < 0) {
				ThisSum = 0;					//如果当前子列和为负,则不可能使后面的部分和增大,抛弃之
				t = i+1;						//更新连续序列的首元素位置为当前位置的下一个位置
			}
		}

		if (MaxSum >= 0) {//MaxSum有更新过,序列不是全为负的情况
			System.out.println(MaxSum + " " + a[left] + " " + a[right]);
		} else {//MaxSum没有更新过,说明序列是全为负的情况
			System.out.println(0 + " " + a[0] + " " + a[a.length-1]);
		}
	}
}

测试情况:
Maximum Subsequence Sum_第1张图片

你可能感兴趣的:(算法)