skip to Main Content

Return the string true if any two numbers can be multiplied so that the answer is greater than double the sum of all the elements in the array. If not, return the string false.

let arr = [2,2,2,2,4,1]
function SumMultiplier(arr) { 

  let sum = arr.reduce((acc, item) => acc +item,0)
  let trueStr = "true"
  let falseStr = "false"
  let double = sum*2
  let arrLength = arr.length
  let i = 0
  let j = 1
  while(i < arrLength){
    let multi = arr[i] * arr[j]
    if(double < multi) {
      j++
    }else{
      return trueStr
    }
  }
  return falseStr 

}

i found double the sum of all elemets in array, but cant solve multiplaction each element in array.

3

Answers


  1. You can find tho largest element in the array, multiply them and then compare result with the doubled sum.

    function SumMultiplier(arr) {
      const target = arr.reduce((acc, item) => acc + item, 0) * 2;
      const [largest, secondLargest] = findTwoLargest(arr)
    
      return largest * secondLargest > target ? "true" : "false"
    }
    
    function findTwoLargest(arr) {
      let largest = arr[0];
      let secondLargest = -Infinity;
    
      for (let i = 1; i < arr.length; i++) {
        if (arr[i] > largest) {
          secondLargest = largest;
          largest = arr[i];
        } else if (arr[i] > secondLargest && arr[i] < largest) {
          secondLargest = arr[i];
        }
      }
    
      return [largest, secondLargest];
    }
    
    console.log(SumMultiplier([2, 2, 2, 2, 4, 1]))
    Login or Signup to reply.
  2. Assuming that you don’t care if the number multiplies by itself, try using nested loops, it’s easier. This way you check every element with the other ones including itself.

    Something like:

    for (var i = 1; i < arr.length; i++) {
    
       for (var j = 1; j < arr.length; j++) {
    
           if(arr[i] * arr[j] > sumDouble){
    
                return 'true';
           }
       }
    }
    
    Login or Signup to reply.
  3. as @tkausl comented

    let arr = [2,2,2,2,4,1]
    
    function SumMultiplier(arr) {
       let sum = arr.reduce((partialSum, a) => partialSum + 2*a, 0);
       let b = arr.slice(0).sort((e1, e2) => e2 - e1)
       let r = b[0] * b[1]
       return (r > sum) ? "true": "false"
    }
    

    after @Nina Scholz coment modify sort() to sort((e1, e2) => e1 – e2)

    @tatactic coment => sort((e1, e2) => e2 – e1)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search