skip to Main Content

Here is my code, is there a possible way to get the element highest sum all i know is to summing up a 2d array. but what i want is get element whose has a highest value when you sum them up check my code

const sumof2dArray = (arr) => {
    let newArr = []
    for(let i = 0; i < arr.length;i++){
        let sum = 0
        console.log(arr[i])
        for(let j = 0; j < arr[i].length;j++){
   
            sum = sum + arr[i][j] 
            
        }
        newArr.push(sum)
        console.log(sum)
    }
    let max = newArr[0]
    for(let i of newArr){
        if(i > max){
            max = i
        }
    }
    return max
}
sumof2dArray([[1,2,3], [4,5,6], [10,11,12], [7,8,9],[1,3,40]])

my output is: 44

but what i want is the element expected output should be: [1,3,40]

5

Answers


  1. Use two variables, one to hold the highest sum, and another to hold the array that has that sum. Then loop through the 2D array, updating those variables whenever a row’s sum is higher than the max.

    const sumof2dArray = (arr) => {
      let maxRow = arr[0];
      let maxSum = sumOfArray(maxRow);
      
      for (let i = 1; i < arr.length; i++) {
        let newSum = sumOfArray(arr[i]);
        if (newSum > maxSum) {
          maxRow = arr[i];
          maxSum = newSum;
        }
      }
      
      return maxRow;
    
      function sumOfArray(arr) {
        let sum = 0;
        for (let j = 0; j < arr.length; j++) {
          sum = sum + arr[j]
        }
        return sum;
      }
    }
    
    console.log(sumof2dArray([
      [1, 2, 3],
      [4, 5, 6],
      [10, 11, 12],
      [7, 8, 9],
      [1, 3, 40]
    ]))
    Login or Signup to reply.
  2. The 44 comes from when you write

    console.log(sum)
    

    But you are doing nothing with the return value of the function.
    If you want it to output the return value, just replace

    sumof2dArray([[1,2,3], [4,5,6], [10,11,12], [7,8,9],[1,3,40]])
    

    with

    console.log(sumof2dArray([[1,2,3], [4,5,6], [10,11,12], [7,8,9],[1,3,40]]))
    
    Login or Signup to reply.
  3. You can traverse all subarrays. USE two sub-variables, one to store the sub-array with the largest sum, the other to store the position of the sub-array with the largest sum

    const highestSumElement = (arr) => {
        if (!arr || arr.length == 0) {
            return []
        }
        
        let maxSum = 0
        let maxIndex = -1
      
        arr.forEach((item, idx) => {
            let sum = arr[idx].reduce((a, b) => a + b)
            if (sum > maxSum) {
                maxSum = sum
                maxIndex = idx
                
            }
            
        })
    
        return arr[maxIndex]
    }
    
    console.log(highestSumElement([[1,2,3], [4,5,6], [10,11,12], [7,8,9],[1,3,40]]))
    
    Login or Signup to reply.
  4. Here’s another method using Array#reduce.

    const sum = arr => arr.reduce((a, b) => a + b, 0);
    const sumof2dArray = arr => arr.reduce((acc, curr) => sum(curr) > sum(acc) ? curr : acc);
    console.log(sumof2dArray([[1,2,3], [4,5,6], [10,11,12], [7,8,9],[1,3,40]]));
    Login or Signup to reply.
  5. Here are a couple answers you can use.

    I think the first is more intuitive, just keeping track of the max array at the same time as the max sum.

    The second one is just using reduce inside of reduce to narrow down to the highest array.

    It can be helpful to initialize max to -infinity in case you have negative values in your sub arrays. If they were all negative for example, you’d never find any summed array with a higher value than the initial max. That also allows you to then start a loop at the beginning of the array, and not have to treat the first element separately.

    Each of these examples only has to sum each sub array once.

    const arr = [
      [1, 2, 3],
      [4, 5, 6],
      [10, 11, 12],
      [7, 8, 9],
      [1, 3, 40],
    ];
    
    const sumof2dArray = (arr) => {
      let res;
      let max = -Infinity;
    
      for (a of arr) {
        const sum = a.reduce((a, b) => a + b, 0);
        if (sum > max) {
          max = sum;
          res = a;
        }
      }
    
      return res;
    };
    
    sumof2dArray(arr);
    
    const sumof2dArray2 = (arr) =>
      arr.reduce(
        (prev, curr) => {
          sum = curr.reduce((a, b) => a + b, 0);
          return sum > prev[1] ? [curr, sum] : prev;
        },
        [[], -Infinity]
      )[0];
    
    sumof2dArray2(arr);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search