Skip to content

Instantly share code, notes, and snippets.

@jikeytang
Created May 20, 2014 03:49
Show Gist options
  • Save jikeytang/6d8d90c633f9df9e91c2 to your computer and use it in GitHub Desktop.
Save jikeytang/6d8d90c633f9df9e91c2 to your computer and use it in GitHub Desktop.
[ Javascript ] - 20140520-题目3
由杭州-轨道友情提供,也可直接到[csdn答题](http://blog.csdn.net/chriswenwu/article/details/26354361):
求子数组的最大和
一个整型数组,数组里有正数和负数。数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和,求所有子数组的和的最大值。
回复时注意加上下面这句话,才会有语法高亮或格式缩进。
```javascript
@chriswenwu
Copy link

//求子数组的最大和 北京-小武提供
//利用的是dp的思想,依次遍历数组中的每个元素,把他们相加,如果加起来小于0,则
//把当前元素之和清为0,否则则和最大和比较,更新最大和,最后得到必是子数组的最大和

#include<iostream>
using namespace std;
int findGreatestSubSum(const int a[],const int size){
    int curSum=0;
    int maxSum=0;
    for(int i=0;i<size;i++){
        curSum+=a[i];
        if(curSum<0) curSum=0; //放弃这个阶段,从新开始
        if(curSum>maxSum) maxSum=curSum; //更新最大和
    }
    if(maxSum==0){ //若是数组中的元素均为负数,则输出里面的最大元素
        maxSum=a[0]; //当然这步也可以写到上面一个循环里
        for(int i=1;i<size;i++){
            if(maxSum<a[i]) maxSum=a[i];
        }
    }
    return maxSum;
}
int main(void){
    int a[10]={1, -2, 3, 10, -4, 7, 2, -5};
    cout<<findGreatestSubSum(a,10)<<endl;
    system("pause");
    return 0;
}

@jiangtao
Copy link

题目没看太懂

@zjhsd2007
Copy link

function get(arr){
    var c1, c2, ret = [], p = 0, i = 1, j;
    arr.push('#');
    c1 = arr[0];
    for (j = arr.length; i < j; i++) {
        c2 = arr[i];
        if (c2 == '#' || Math.abs(c2) - Math.abs(c1) != 1) {
            if (i - p >= 2) {
                ret.push(eval(arr.slice(p, i).join('+'))); 
            }
            p = i;  
        }
        c1 = c2;
    }
    return Math.max.apply(null,ret);
}
console.log(get([1,2,4,5,6,8,2,5,6,7,8,-1,-2,-3]))

@rambo-panda
Copy link

var build_arr = (function() {

        var length = 200,
            arr_more = [],
            random;

        while (length > -1) {
            random = Math.random();
            var len = parseInt(random * 50),
                arr = [];

            length -= len;
            while (--len) {
                random = Math.random();
                arr.push((random > 0.5 ? -1 : 1) * window.parseInt(random * len))
            }
            arr_more.push(arr);
        }
        return arr_more;

    })(),
    length = build_arr.length,
    max = 0,
    total = 0;


while (--length > -1) {
    var arr = build_arr[length];
    max = Math.max(Math.max.apply(window, arr), max);

    total += new Function('return ' + arr.join('+'))();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment