最長子串

求數組的最長子串



var fn = function(arr,sum,index,len) {
    // 無法取的情況
    if(index+len == arr.length){
        return {sum,index,len};
    }

    // 能取的情況
    var list = [];
    // 1.不取
    var notFetch = sum;
    // 2.取下一個
    var fetch = sum+arr[index+len];
    // 如果多fetch一個數字,不比notFetch大,則push notFecth
    if(fetch<notFetch){
        list.push({sum:notFetch,index,len});
    }
    // 2.1 使得sum爲負

    // 2.2 使得sum不爲負
    if(fetch>=0){
        list.push(fn(arr,fetch,index,len+1));
    }else{
        // 2.3 放棄已經fetch的
        list.push(fn(arr,0,index+1,0));
    }

    return max(list);

};

function max(arr){
    return arr.sort(function(a,b){
        return b.sum - a.sum;
    })[0];
}

console.log(fn([1, 5, -7, 2, 6, -1, 5],0,0,0));
console.log(fn([1, 5, -7, 2, 6, -11, 5],0,0,0));
console.log(fn([1, 5, -4, 2, 6, -1, 5],0,0,0));
console.log(fn([-3,-1],0,0,0));

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章