1
function FindGreatestSumOfSubArray(arr)
{
    if(arr.length === 0)
        return;
    if(arr.length === 1)
        return arr[0];
    var allNeg = true;
    var negMax = -Infinity;
    for(var i = 0;i < arr.length;i++) {
        if(arr[i] > negMax){
            negMax = arr[i];
        }
        if(arr[i] >= 0){
            allNeg = false;
        }
    }
    
    if(allNeg)
        return negMax;
    
    var max = -Infinity, cur = 0;
    
    for(var i = 0;i < arr.length;i++) {
        cur += arr[i];
        max = Math.max(max, cur);
        cur = cur >=0 ? cur : 0;
    }
    
    return max;
}

耳东
766 声望51 粉丝

知乎专栏:[链接]