题目描述:输入一个整型数组,元素有正数,也有负数。数组中一个或者多个组成一个子数组,求所有子数组中的最大值为多少?
举例:{1 , -2 , 3 ,10 , -4 ,7 ,2 ,-5} ,那么最大子数组为{3 ,10 , -4 , 7 , 2}。最大值为18;
思路一:穷举法
遍历所有连续子数组,比较找出其中子数组值最大的一个;
MaxSum[i .....j] 为数组data中第i个到第j个的连续和,其中 0 <= i <= j < length;遍历所有可能的MaxSum[i........j];
思路二:
当前子数组之和:CurrentSum;
最大子数组之和:MaxSum;
若CurrentSum <= 0:则 CurrentSum + data[i] <= data[i] ;CurrentSum没有必要再加下去,其需要更新为:data[i];
若CurrentSum > 0; 则 CurrentSum += data[i];
若CurrentSum > MaxSum: 则MaxSum = CurrentSum;
代码实现:
#include<iostream>
using namespace std;
//---------------------------------------------连续子数组的最大和---------------------------------------
//无效输入
bool InvalidInput = false;
int TheGreatestOfSum_Soulation1(int* data , int length)
{
if(data == NULL || length <= 0)
{
InvalidInput = true;
return 0;
}
bool InvalidInput = false;
int MaxSum = 0;
int CurrentSum = 0;
for(int i = 0; i < length; ++i)
{
for(int j = i; j < length; ++j)
{
for(int k = i; k <= j; ++k)
{
CurrentSum += data[k];
}
if(CurrentSum > MaxSum)
MaxSum = CurrentSum;
CurrentSum = 0;
}
}
return MaxSum;
}
int TheGreatestOfSum_Soulation2(int* data , int length)
{
if(data == NULL || length <= 0)
{
InvalidInput = true;
return 0;
}
InvalidInput = false;
//0x80000000:16进制表示-0;
//为了预防元素皆为负数;
int MaxSum = 0x80000000;
int CurrentSum =0;
for(int i = 0; i < length; ++i)
{
if(CurrentSum <= 0)
CurrentSum = data[i];
else
CurrentSum += data[i];
if(CurrentSum > MaxSum)
MaxSum = CurrentSum;
}
return MaxSum;
}
int main()
{
//数组元素:有正 ,有负
int data1[] = {-2 , -3 , -1 , -5 , -9 , -8 , 10};
int result1 = TheGreatestOfSum_Soulation1(data1 , 7);
cout<<result1<<endl;
int data2[] = {2 , 3 , -1 , -5 , -9 , -8 , 10};
int result2 = TheGreatestOfSum_Soulation2(data2 , 7);
cout<<result2<<endl;
//数组元素:皆负
int data3[] = {-6 , -3 , -4 , -5 , -9};
int result3 = TheGreatestOfSum_Soulation2(data3 , 5);
cout<<result3<<endl;
//数组元素:皆正
int data4[] = {2 , 3 , 4 , 1, 6 , 7};
int result4 = TheGreatestOfSum_Soulation2(data4 , 6);
cout<<result4<<endl;
//输入为NULL
int result5 = TheGreatestOfSum_Soulation2(NULL , 0);
cout<<result5<<endl;
return 0;
}