最大连续子序列和

来源:互联网 发布:怎样才能把淘宝店做好 编辑:程序博客网 时间:2024/04/26 02:08

题目

求数组中最大的连续序列的和,如果数组元素全为负数返回0

做法及代码

蛮力法

遍历 以i为起点,长度为1  -  n-i+1  ,i =0 ... n-1 ,时间复杂度O(n^2)

int maxSeq(int *arr,int num,int&start,int&end){        int ret=0;        start=-1;        end=-1;        int s=0;        for(int i=0;i<num;++i){                int maxLen=num-i;                int temp=0;                for(int len=1;len<=maxLen;++len){                        temp+=arr[i+len-1];                        if(temp>ret){                                ret=temp;                                start=i;                                end=i+len-1;                        }                }        }        return ret;}

动态规划法

动态规划,依次加入数组中元素进行统计,时间复杂度O(n)

//dpint maxSeqDP(int *arr,int num,int&start,int&end){        int ret=0;        int temp=0;        start=-1;        end=-1;        int s=0;        for(int i=0;i<num;++i){                temp+=arr[i];                if(temp<0){                        temp=0;                        s=i+1;                }else if(temp>ret){                        ret=temp;                        start=s;                        end=i;                }        }        return ret;}

测试代码

#include <iostream>#include <cstdlib>int main(int argc,char** argv){        int num=10;        if(argc>=2)                num=atoi(argv[1]);        int *arr=new(std::nothrow) int [num];        srand(time(NULL));        for(int i=0;i<num;++i){                arr[i]=rand()%1000>=400?rand()%99:rand()%99*-1;                std::cout<<arr[i]<<",";        }        std::cout<<std::endl;        int start=0,end=0;        std::cout<<maxSeq(arr,num,start,end);        std::cout<<",["<<start<<","<<end<<"]"<<std::endl;        std::cout<<maxSeqDP(arr,num,start,end);        std::cout<<",["<<start<<","<<end<<"]"<<std::endl;        delete []arr;        return 0;}

参考

参考下面这篇博客,不同的是,这位作者在数组中元素全为负数的时候,返回的是最小的负数。

http://blog.csdn.net/sgbfblog/article/details/8032464


0 0