###### 微软等公司数据结构面试题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;

}

#### 微软等公司数据结构+算法面试题系列

2010年11月28日 8KB 下载

#### 微软公司等数据结构+算法面试100题

2016-07-11 11:02:22

#### 微软等数据结构+算法面试100题全部答案集锦

2011年10月15日 370KB 下载

2016-07-13 15:29:56

#### 微软等数据结构 算法面试100题全部答案集锦

2018年01月23日 524KB 下载

#### 微软等公司的面试题

2018年01月11日 112KB 下载

#### 2017微软面试算法题回顾

2017-04-25 12:15:54

#### 各大公司数据结构与算法面试题解答(一)

2012-11-19 21:19:21

2016-08-20 15:24:16

#### 微软面试题--三个灯泡--三个开关

2015-08-07 09:00:23