首页 > 编程语言 > 详细

最大连续子数组,线性时间解法

时间:2017-09-20 12:44:49      阅读:288      评论:0      收藏:0      [点我收藏+]

思想:

经过分析可得,若子数组和为负数就已经代表这个子数组不可能为最大子数组了,相反若子数组和为正,则将最大的和比较出来便可。

故可直接遍历该数组一旦子数组和已为负数,则置为0,否则与之前的最大值进行比较,得出目前最大值。

上代码:

#include<iostream>
using namespace std;

int getMax(int *arr,int n,int start,int end){
    
    int max;
    int firstmax = arr[0];
    max = arr[0];
    for(int i=1;i<n;i++){
        if(firstmax<0){
            firstmax = arr[i];
            start = i;
        }else{
            firstmax += arr[i];
        }
        if(firstmax > max){
            max = firstmax;
            end = i;
        }
    }
    printf("数组下标为%d到%d,和为%d\n",start,end,max);
    return max;
    
}

int main(){
    int a[100];
    int n;
    int start=0,end=0;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    getMax(a,n,start,end);
    return 0;
}

 

最大连续子数组,线性时间解法

原文:http://www.cnblogs.com/tz346125264/p/7560708.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!