题目:求子数组的最大和 输入一个整形数组,数组里有正数也有负数。数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。求所有子数组的和的最大值。要求时间复杂度为 O(n) 。 例如输入的数组为 1, -2, 3, 10, -4, 7, 2, -5 ,和最大的子数组为 3, 10, -4, 7, 2 ,因此输出为该子数组的和18 。
分析:
如果第一次遇见这样的题目,在时间复杂度为O(n)的条件下,似乎不能做到。而最容易想到的就是穷举法了,元素个数为1的子数组有n个,元素个数为2的子数组有n-1,……这样下去,明显不符合时间复杂度O(n)的要求。该怎么办呢?贪心算法!以上面的数组为例,首先初始化子数组和的最大值max为0,数组元素和sum为0,从第一个元素开始计算,若相加后的sum为正,且sum>max,则max=sum,若sum<0,则sum=0,依次计算下去,……
然而这样会有一种特殊情况,即数组的全部元素均为负数,此时最后的max=0,不是子数组和的最大值(应该为数组元素中值最大的一个负数)。解决该特殊情况最容易想到的方法就是重新循环一次数组(不好,又循环了一次),找出最大值,或者在第一次循环时顺便找出最大值,此种情况的代码如下
#include <iostream>
int maxsubarr(int *arr,int size);
int main()
{
using namespace std;
int arr[8] = {-1,-2,3,-1,4,-7,-2,-5};
int max = maxsubarr(arr,8);
cout<<max<<endl;
system("pause");
return 0;
}
int maxsubarr(int *arr,int size)
{
int maxsub = 0;
int max = arr[1];
int sum = 0 ;
for (int i=0;i<size;i++)
{
sum = sum + arr[i] ;
if (sum>0&&sum>maxsub)
maxsub = sum ;
if (sum<0)
sum = 0;
if (arr[i]>max)
max = arr[i] ;
}
if (maxsub==0)
maxsub = max ;
return maxsub ;
}
下面一段代码如何打印这些数据
#include <iostream>
using namespace std;
int maxsubarr(int *arr,int size);
int main()
{
using namespace std;
int arr[18] = {-7,8,-4,6,-2,-12,3,7,19,-12,-16,2,5,7,19,-2,1,2};
int max = maxsubarr(arr,18);
cout<<max<<endl;
system("pause");
return 0;
}
int maxsubarr(int *arr,int size)
{
int maxsub = 0;
int max = arr[1];
int sum = 0 ;
int begin = 0;
int end = 0;
int tempbegin = 0;
int tempend = 0;
for (int i=0;i<size;i++)
{
sum = sum + arr[i] ;
if (sum>0&&sum>maxsub)
{
maxsub = sum ;
end = i;
tempbegin = begin ;
tempend = end ;
}
if (sum<0)
{
maxsub = 0;
sum = 0;
begin = i+1 ;
}
if (arr[i]>max)
max = arr[i] ;
}
if (maxsub==0)
maxsub = max ;
for (int j=tempbegin;j<=tempend;j++)
{
cout<<arr[j]<<" ";
}
cout<<endl;
return maxsub ;
}
431

被折叠的 条评论
为什么被折叠?



