# 微软等公司数据结构面试题3

3.求子数组的最大和（数组）

#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;

}

max （a[i-1]的最大子数组  or a[i]最靠近右边大于零的子数组）  a[i]>=0 a[i-1]的最大子数组右值下标不为i-1

#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;

}

• 本文已收录于以下专栏：

举报原因： 您举报文章：微软等公司数据结构面试题3 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)