求最大子数组

求一组数列的最大字数组,并求出位置,遍历一遍即可。

#include <stdio.h>   
#include <iostream>
#include  <vector>
using namespace std;
const int numCount=20;
int numArray[numCount]={11,3,-3,2,45,-6,5,-75,75,-1,-21,-77,-8,-2,-72,-14345,-3245,-55,-28,1111134};
int index1=0,index2=0;

void maxSubArry(){
int max =numArray[0];
int tempMax=0;
int start=0;
int end=0;
int fstart=0,fend=0;
bool first=true;
	for(int i=0;i<20;++i){
    if(numArray[i]+tempMax>0){
    	if(first){
    		start=i;
    		first=false;
    	}
    tempMax+=numArray[i];
    if (tempMax>max){
    	// cout<<"tempMax"<<tempMax<<"i"<<i<<endl;
    	end=i;
    	fstart=start;
    	max=tempMax;
        }
	}
	else{
		tempMax=0;
        first=true;
	}
}
cout<<"max is:"<<max<<" from :"<<fstart<<" to :"<<end;
}






int  main()
{
	maxSubArry();
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值