题目:输入一个整型数组,数组里有正数也有负数。数组中一个或连续的多个整数组成一个子数组。求所有子数组的和的最大值。要求时间负责度为O(n);
头文件
#pragma once
#include <iostream>
class theMaxSub
{
private:
int theBig;
int start;
int end;
public:
friend std::ostream& operator<<(std::ostream &os, theMaxSub maxSub);
theMaxSub(void);
~theMaxSub(void);
void settheBig( int value );
void setstart ( int value );
void setend ( int value );
void findbyOrder (int *array, int len);
};
类的实现
#include "stdafx.h"
#include "theMaxSub.h"
theMaxSub::theMaxSub(void):theBig(-1),start(-1),end(-1)
{
std::cout<<*this;
}
theMaxSub::~theMaxSub(void)
{
}
std::ostream& operator<<(std::ostream &os, const theMaxSub maxSub)
{
os<<"the Max Sub array is:"<<maxSub.theBig<<std::endl;
os<<"the start index is:"<<maxSub.start<<std::endl;
os<<"the end index is:"<<maxSub.end<<std::endl;
return os;
}
void theMaxSub::settheBig( int value )
{
this->theBig = value;
}
void theMaxSub::setstart ( int value )
{
this->start = value;
}
void theMaxSub::setend ( int value )
{
this->end = value;
}
void theMaxSub::findbyOrder (int *array, int len)
{
if ( array == NULL || len < 0 )
{
return ;
}
//int i = 0;
int sumAry = -1;
int startpos = -1;
for (int i = 0; i < len ; i++ )
{
if (sumAry < 0)
{
sumAry = array[i];
startpos = i;
}
else
{
sumAry += array[i];
}
if ( sumAry > this->theBig)
{
this->settheBig( sumAry );
this->setstart( startpos );
this->setend ( i );
}
}
std::cout<<*this;
}
// MaxSubArray.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include "theMaxSub.h"
int _tmain(int argc, _TCHAR* argv[])
{
//define the array
int a[] = {2,5,8,3,-4,7,-9,10,-4,-23};
int len = sizeof(a)/sizeof(int);
theMaxSub theMax;
theMax.findbyOrder(a,len);
}