最大子数组问题

题目:输入一个整型数组,数组里有正数也有负数。数组中一个或连续的多个整数组成一个子数组。求所有子数组的和的最大值。要求时间负责度为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);
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值