一个包含正整数和负整数的数组,找出和最大的子串.

一个包含正整数和负整数的数组,找出和最大的子串.

 

Eg:int x[15] = {2,3,-5,5,6,-5,-1,14,9,-10,1,-1,75,4,-9};


给定一个整型数组a,求出最大连续子段之和

/*FindMaxSub.cpp
*by wangzhihong
*05/01/2007
***************
*specification: find the substring in an array which has the maximun sum
*/

#include <iostream>
using namespace std;


int FindMaxSub(int array[],int len,int &start,int &end)
{
    int max,sum;
    int i,temps;

    start=end=temps=max=sum=0;

    for(i=0;i<len;++i)
    {
        //there's no need to do this swap everytime when sum>max,
        //because if array[i]>0 the sum will always increase
        if(array[i]<0&&sum>max)
        {
            max=sum;
            start=temps;
            end=i-1;
        }

        //if the substring start from the next one,
        //we should not add the whole prestring because its sum is minus
        if(array[i]+sum<0)
        {
            sum=0;
            temps=i+1;
            continue;
        }

        sum+=array[i];
    }

    //if the last one is used,
    //we should assign the max and end here
    if(sum>max)
    {
        max=sum;
        start=temps;
        end=i-1;
    }

    return max;
}

int FindMaxSub2(int array[],int len,int &start,int &end)
{
	int sum,max;
	start=end=0;
	max=sum=array[0];

	for (int i=1;i<len;++i)
	{
		if(sum<=0 && summax)	{
				start=end=i;
				max=sum;
			}
		}	else	{
			sum+=array[i];
			if(sum>max)		{
				end=i;
				max=sum;
			}
		}
	}
	return max;
}

int main(void)
{
    int *array;
    int len,start,end;
    int i;

    cin>>len;
    array=new int[len];
    for(i=0;i<len;++i)
        cin>>array[i];

    cout<<"Max Subvalue: "<<FindMaxSub(array,len,start,end)<<endl;
    cout<<"From: "<<start<<" To: "<<end<<endl;
    delete[] array;

    return 0;
}

来自其评论:http://blog.sina.com.cn/s/blog_4bd02c41010008ue.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值