JSFiddle - React, Tailwind, and code Playground

by adnane_ka

JavaScript

var arr = [-1, 2, 3, -9];


/**
* summarize the proccess
* @param arr : array 
* @return int 
*/
function getMaxSubSum(arr)
{
    var all = getAllPossibleSums([],arr);

    return getMaxNum(all);   
}

/**
* get all the possible sums that we can form from a given array 
* @param group : array , sub_group: array
*/
var sums = [];
function getAllPossibleSums(group, sub_group)
{
    if( group.length == arr.length || (group.length <= arr.length && sub_group.length == 0) ){
        
        if( group.length > 0 ){

            var total = group.reduce(function(a,b){return a+b;},0);
            
            if(sums.indexOf(total) == -1){
                sums.push(total);
            }

        }
    }
 
    else{
       getAllPossibleSums(group.concat(sub_group[0]),sub_group.slice(1));

       getAllPossibleSums(group,sub_group.slice(1));
    }

    return sums;
}

/**
* get the maximum value in a list of a numbers
* @param group : array , sub_group: array
*/
function getMaxNum(arr){
    let i;

    let max = arr[0];

    for (i = 1; i < arr.length; i++) {
        if (arr[i] > max){
            max = arr[i];
        }
    }
      
    return max;
}

console.log( getMaxSubSum(arr)); // 5
sums = [];
console.log( getMaxSubSum([-1, 2, 3, -9, 11]) ); // 11 + 3 + 2 
sums = [];
console.log( getMaxSubSum([-2, -1, 1, 2]) ); // 2 + 1 
sums = [];
console.log( getMaxSubSum([1, 2, 3]) ); // 1 + 2 + 3
sums = [];
console.log( getMaxSubSum([100, -9, 2, -3, 5]) ); // 5 + 100 + 2