3.求子数组的最大和(数组)
题目:
输入一个整形数组,数组里有正数也有负数。
数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。
求所有子数组的和的最大值。要求时间复杂度为O(n)。
例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,
因此输出为该子数组的和18。
#include <iostream>
class Array
{
public:
Array(int a[],int length):m_array(a),m_length(length) {}
void Findbest();
void Print();
private:
int *m_array;
int m_left;
int m_right;
int m_length;
int m_nearLeft;
int m_nearRight;
int m_max;
int m_nearMax;
};
void Array::Findbest()
{
m_left = 0;
m_right = -1;
m_nearLeft = 0;
m_nearRight = -1;
m_max = m_nearMax = 0 ;
for (int i = 0 ; i < m_length ; i++ )
{
if ( m_array[i] >= 0 ) {
if ( m_nearRight + 1 == i ) {
m_nearMax += m_array[i] ;
m_nearRight = i ;
}
else {
m_nearLeft = m_nearRight = i;
m_nearMax = m_array[i] ;
} // else if ( m_nearRight +1 == i )
if (m_right + 1 == i) {
m_right = i;
m_max += m_array[i];
}
else {
if ( m_max < m_nearMax ) {
m_max = m_nearMax ;
m_left = m_nearLeft ;
m_right = m_nearRight ;
}
} //else if (m_right +1 == i)
} //end if ( m_array[i] >= 0 )
else {
if ( m_nearRight + 1 == i && m_nearMax + m_array[i] > 0 ) {
m_nearMax += m_array[i] ;
m_nearRight = i ;
}
else {
m_nearLeft = m_nearRight = 0;
}
}
} //end of for
}
void Array::Print()
{
std::cout<<"left="<<m_left+1<<" right="<<m_right+1<<std::endl;
std::cout<<"Total is "<<m_max<<std::endl;
for(int i = m_left ; i <=m_right ; i++ ) {
std::cout<<m_array[i]<<" ";
}
std::cout<<std::endl;
}
int main()
{
int t[]={-1,-2,3,10,-4,7,2,-5};
Array a(t,8);
a.Findbest();
a.Print();
getchar();
return 0;
}
利用动态规划的思想:
当前a[i]的最大子数组等于 a[i-1]的最大子数组 + a[i] a[i]>=0 a[i-1]的最大子数组右值下标为i-1
max (a[i-1]的最大子数组 or a[i]最靠近右边大于零的子数组) a[i]>=0 a[i-1]的最大子数组右值下标不为i-1
当 a[i] <0 时 仅需要对 a[i]最靠近右边大于零的子数组 进行处理即可:
当 a[i-1]最靠近右边大于零的子数组 + a[i] >= 0 时 子数组增加
否则对子数组清空
上面的思路比较复杂 下面的判断简化,只需要用最近的记录的和和以前的最大值比较,如果记录的最近的和小于0,则重新记录
#include <iostream>
class Array
{
public:
Array(int a[],int length):m_array(a),m_length(length) {}
void Findbest();
void Print();
private:
int *m_array;
int m_left;
int m_right;
int m_length;
int m_nearLeft;
int m_nearRight;
int m_max;
int m_nearMax;
};
void Array::Findbest()
{
m_left = 0;
m_right = -1;
m_nearLeft = 0;
m_nearRight = -1;
m_max = m_nearMax = 0 ;
for (int i = 0 ; i < m_length ; i++ )
{
m_nearMax += m_array[i];
m_nearRight++;
if (m_nearMax > 0)
{
if ( m_nearMax > m_max)
{
m_max = m_nearMax;
m_left = m_nearLeft;
m_right = m_nearRight;
}
}
else
{
m_nearMax = 0;
m_nearLeft = i + 1 ;
m_nearRight = i;
}
} //end of for
}
void Array::Print()
{
std::cout<<"left="<<m_left+1<<" right="<<m_right+1<<std::endl;
std::cout<<"Total is "<<m_max<<std::endl;
for(int i = m_left ; i <=m_right ; i++ ) {
std::cout<<m_array[i]<<" ";
}
std::cout<<std::endl;
}
int main()
{
int t[]={-1,-2,3,10,-4,7,2,-5};
Array a(t,8);
a.Findbest();
a.Print();
getchar();
return 0;
}