首页 > 其他 > 详细

求子数组最大和以及字数组组成

时间:2014-03-05 03:55:28      阅读:362      评论:0      收藏:0      [点我收藏+]

题目:输入一个整形数组,数组里有正数也有负数。数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。求所有子数组的和的最大值。要求时间复杂度为O(n)

例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,因此输出为该子数组的和18

分析:

当加上一个正数时,和会增加;当加上一个负数时,和会减少。如果当前得到的和是个负数,那么这个和在接下来的累加中应该抛弃并重新清零,不然的话这个负数将会减少接下来的和。基于这样的思路,可以写出如下代码。

 

/*This is the template of *.cpp files */
#include<iostream>
using namespace std;
int sub_max(int *in, int len){
    int front = 0;
    int end = 0;
    int max = 0;
    int b = 0;
    int i = 0;
    int j = 0;
    for(int k = 0; k < len; ++k){
        b += in[k];
        if(b < 0){
            i = k + 1;
            j = k + 1;
            b = 0;
        }else{
            j = k;
            if(b > max){
                front = i;
                end = j;
                max = b;
            }
        }
    }
    for(int l = front; l <= end; ++l){
        cout<<in[l]<<"    ";
    }
    cout<<endl;
    return max;
}
int main(){
    int test[8] = {1,-2,3,10,-4,7,2,-5};
    cout<<sub_max(test, 8);
    return 0;
}

求子数组最大和以及字数组组成,布布扣,bubuko.com

求子数组最大和以及字数组组成

原文:http://www.cnblogs.com/candycloud/p/3580466.html

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