问题:输入一个整型数组,数组里有正数也有负数。数组中一个或连续的多个整数组成一个子数组。求所有子数组的和的最大值。要求时间复杂度为O(n)。
补充:这个数组是二维数组或循环数组时,该如何求解?
1.穷举法——时间复杂度为O(n^2),空间复杂度为O(1).
extern bool g_bInvalidParameters;
long findGreatestSumOfSubArrayWithExhausion(int* array, int length) {
g_bInvalidParameters = false;
if (NULL == array || 0 >= length) {
g_bInvalidParameters = true;
return -1;
}
long currentSum = 0L;
long greatestSum = 0x80000000;
for (int i = 0; i < length; ++i) {
currentSum = 0;
for (int j = i; j < length; ++j) {
currentSum = currentSum + array[j];
if (greatestSum < currentSum) {
greatestSum = currentSum;
}
}
}
return greatestSum;
}
2.利用动态规划——时间复杂度为O(n),空间复杂度为O(1).
long findGreatestSumOfSubArrayWithDP(int* array, int length) {
g_bInvalidParameters = false;
if (NULL == array || 0 >= length) {
g_bInvalidParameters = true;
return -1;
}
long currentSum = 0L;
long greatestSum = 0x80000000;
for (int i = 0; i < length; ++i) {
if (currentSum < 0) {//如果当前序列和为负数,则从其当前元素重新计算
currentSum = array[i];
} else {
currentSum = currentSum + array[i];
}
if (greatestSum < currentSum) {
greatestSum = currentSum;
}
}
return greatestSum;
}
声明错误类型
#ifndef CONSTANSTS_H_
#define CONSTANSTS_H_
//输入参数非法
bool g_bInvalidParameters;
#endif /* CONSTANSTS_H_ */
测试代码
/*
*
* Created on: 2014-4-7 16:56:29
* Author: danDingCongRong
*
*/
#include"constants.h"
#include<iostream>
using namespace std;
//输入各个数组元素
void inputArray(int* array, int length) {
if (NULL == array || 0 >= length) {
cout << "Invalid Parameter." << endl;
return;
}
for (int i = 0; i < length; ++i) {
cin >> array[i];
}
}
//遍历输出数组中的各个元素
void outputArray(int* array, int length) {
if (NULL == array || 0 >= length) {
cout << "Invalid Parameter." << endl;
return;
}
for (int i = 0; i < length - 1; ++i) {
cout << array[i] << '\t';
}
cout << array[length - 1] << endl;
}
//copy数组
void copyArray(int* array, int* result, int length) {
if (NULL == array || NULL == result || 0 >= length) {
cout << "Invalid Parameter." << endl;
return;
}
for (int i = 0; i < length; ++i) {
result[i] = array[i];
}
}
int main() {
int length = 0;
cout << "请输入数组的长度:" << endl;
while (cin >> length) {
int* source = new int[length];
inputArray(source, length);
int* x = new int[length];
copyArray(source, x, length);
long greatestSum = 0L;
greatestSum = findGreatestSumOfSubArrayWithExhausion(x, length);
if (!g_bInvalidParameters) {
cout << greatestSum << endl;
} else {
cout << "Invalid Parameter." << endl;
}
copyArray(source, x, length);
greatestSum = findGreatestSumOfSubArrayWithDP(x, length);
if (!g_bInvalidParameters) {
cout << greatestSum << endl;
} else {
cout << "Invalid Parameter." << endl;
}
delete x;
delete source;
cout << "请输入数组的长度:" << endl;
}
return 0;
}
注:部分算法参考自剑指offer