Maximum Subsequence Sum:2004年浙江大学计算机专业考研复试真题

最大连续子序列和:求解与代码实例
本文介绍如何解决最大连续子序列和问题,通过C++代码实现,并提供一个样例输入输出。重点在于理解算法思路和找到最大子序列的起始和结束位置。

01-复杂度2 Maximum Subsequence Sum (25 分)
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

#include<iostream>
using namespace std;
using std::cout;
using std::cin;
int findMaxSubSeq(int A[], int N, int &left, int &right) {
	int ThisSum, MaxSum;
	int i;
    int count=0;
	ThisSum = 0;
    MaxSum=-1;//-1是为了解决输入有负数和零的问题
    left=0;
    right=N-1;
	for (i = 0;i<N;i++) {
		ThisSum += A[i];
        count++;       //统计序列长度
        
		if (ThisSum>MaxSum) {
			MaxSum = ThisSum;
			right = i;
            left=right-count+1;
		}        
		else if (ThisSum<0){
			ThisSum = 0;
            count=0;//序列和为负数时,重新开始统计序列长度
        }
       
            
	}
    
    if(MaxSum==-1){//全为负数时,序列和为零
        MaxSum=0;
    }

	return MaxSum;
}
 
int main() {
 
	int b[10000] = {};
	int num, left, right;
	cin >> num;
	for (int i = 0;i<num;i++) {
		cin >> b[i];
	}
	int xx = findMaxSubSeq(b, num, left, right);
	cout << xx << " " << b[left] << " " << b[right];
	return 0;
}
感谢您的指正。确实,在您提供的代码片段中,`maximum` 和 `maxIndex` 的初始值分别设置为 `-1` 和 `-1`。然而,这种初始化方式并不适用于所有情况,特别是当列表中包含非负整数或更大的数值时。为了确保代码的通用性和正确性,我建议根据具体情况进行初始化。 ### 解释初始化值的选择 1. **初始化为第一个元素**: - 这种做法可以确保无论列表中元素的取值范围如何,算法都能正常工作。 - 如果列表为空,可以在遍历前进行检查并返回适当的默认值(如 `None` 或其他约定的值)。 2. **初始化为固定值(如 `-1`)**: - 这种方法假设列表中的所有元素都大于 `-1`,但这并不总是成立,尤其是当列表中包含负数时。 - 使用固定值可能导致算法无法正确识别最大值,特别是在极端情况下。 ### 补充后的代码 如果您坚持使用 `-1` 作为初始值,以下是相应的代码实现,并附带了对空列表的处理: ```python def findMaximum(elements): # 检查列表是否为空 if not elements: return None, None # 如果列表为空,返回None # 初始化maximum和maxIndex为-1 maximum = -1 maxIndex = -1 # 遍历列表中的每个元素及其索引 for index, value in enumerate(elements): # 如果当前元素大于已记录的最大值或这是第一次比较 if value > maximum or maximum == -1: # 更新最大值和其索引 maximum = value maxIndex = index return maximum, maxIndex # 测试代码 elements = [3, 1, 4, 1, 5, 9] # 调用函数并接收返回值 maximum, maxIndex = findMaximum(elements) # 检查结果是否正确 if maximum == max(elements) and maxIndex == elements.index(max(elements)): print(f'Found maximum {maximum} at index {maxIndex}.') else: print('Something went wrong.') ``` ### 推荐做法 为了避免潜在的错误,推荐将`maximum`初始化为列表的第一个元素,这样可以确保算法在任何情况下都能正确工作: ```python def findMaximum(elements): # 检查列表是否为空 if not elements: return None, None # 如果列表为空,返回None # 初始化maximum为列表的第一个元素 maximum = elements[0] # 初始化maxIndex为第一个元素的索引 maxIndex = 0 # 遍历列表中的每个元素及其索引,从第二个元素开始 for index in range(1, len(elements)): # 如果当前元素大于已记录的最大值 if elements[index] > maximum: # 更新最大值和其索引 maximum = elements[index] maxIndex = index return maximum, maxIndex ``` ### 总结 1. **Python中的控制结构**:包括`if`条件语句用于逻辑判断,以及`for`循环用于迭代序列。 2. **Python函数和返回值**:函数可以接受输入参数并返回输出结果,通过`return`语句指定。 3. **Python列表操作**:包括访问列表元素、获取列表长度等基本操作。 如果您有更多问题或需要进一步的帮助,请随时告诉我!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值