说明:仅仅是看到这个小问题,自己动手写一个,练习练习而已。
问题描述:(From Page 47 in Book <Data Structures and Algorithm Analysis in C++ Third Edition> )
Given(possibly negative) integers A1,A2,...,An,find the maximum value of \sum_(k=i)^jAk.
For convenience, the maximum subsequence sum is 0 if all the integers are negative.
Example:
For input -2,11,-4,13,-5,-2, the answer is 20(A2 through A4).
输入:整数数组
输出:最大顺序子序列和
My solution:
思路很简单,首先明确,目标顺序子序列(即最大顺序子序列)的第一个和最后一个元素一定是正整数,且相邻的非目标元素(如果存在的话)一定是负整数。
这个很容易证明,如果目标顺序子序列的第一个元素和最后一个元素不是正整数,去掉非正整数,子序列和变大;如果相邻的非目标元素不是负整数,加上之后,子序列和变大。例如,对于数组{-2,11,-4,13,-5,-2},首尾的负整数-2是不可能出现在目标顺序子序列中的,即只可能在{11,-4,13}中的某个顺序子序列中。
如果数组元素都是正整数,显然,最大顺序子序列和就是所有元素之和