题目3
输入一个整形数组,数组里有正数也有负数。
数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。
求所有子数组的和的最大值。要求时间复杂度为O(n)。
题目分析
从题目中略微一看,会发现这是一个经典算法,考察的是子序列求和问题。
而要求时间复杂度是O(n)。那么很快就可以写出如下代码
#include <stdio.h>
#include <vector>
#include <iostream>
using namespace std;
#define dataType int
dataType getMaxSqu(vector<dataType>& obj) {
dataType maxSum = 0;/* 最大子序列和 */
dataType thisSum = 0;/* 当前最大子序列和 */
/* 遍历输入序列 */
for (int i = 0; i < obj.size(); i++) {
thisSum+=obj[i];
if (thisSum > maxSum) {
maxSum = thisSum;
} else if(thisSum < 0) {
thisSum = 0;
}
}
return maxSum;
}
对算法进行测试,测试程序:
/* 输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2 */
int test_3() {
// 初始化参数
dataType a[] = {1, -2, 3, 10, -4, 7, 2, -5};
int count = sizeof(a)/sizeof(dataType);
vector<dataType> obj(a, a + count);
cout<<"最大子数组和:"<<getMaxSqu(obj)<<endl;
return 0;
}
int main() {
test_3();
return 0;
}
程序打印输出:
路漫漫,吾将上下而求索…