TechnoCorner
TechnoCorner

Reputation: 5155

How would you find the highest three numbers in an array?

I was given a question:

Given an arrayOfInts, find the highestProduct you can get from three of the integers.

Input: var a = [1,7,9,2]; Expected Output: 7*9*2 = 126

How would we solve this problem? I've written the code but in vain.

function highestProductIntegers(a){
  var h1, h2,h3; //three highest number pointers.

  a.forEach(function(val, index){
    if(index=0){
      h1 = val; //assign the first element to h1 (Highest 1)
    }

    h2 = val; //second to h2

    if( val > h1 ){ //if second is greater than h1 make it h1 || h2 || h3
      h3 = h2;
      h2 = h1;
      h1 = val;
    }
    else if(val<h1 && val > h2) //keep comparing for all elements.
      h2 = val;
    else if(val < h1 && val < h2)
      h3 = val;
    else if(val < h1 && val < h2 && val > h3)
      h3=val;
  });

    return h1*h2*h3; 
}

Is there any easier or efficient way of solving this problem?

Upvotes: 2

Views: 240

Answers (2)

Para&#237;so
Para&#237;so

Reputation: 384

function highestProductIntegers(array){
array.sort(function(i,k){return k-i;});
return array[0]*array[1]*array[2];
}

Upvotes: 0

kind user
kind user

Reputation: 41893

Three short steps.

  • sort them in a descending order.
  • slice it to get the three (highest) integers
  • use reduce function to multiply it and get the result.

var a = [17, 1, 7, 9, 2, 5, 9, 15, 12, 44],
    r = a.sort((a, b) => b - a).slice(0, 3).reduce((a, b) => a * b);
    console.log(r);

Upvotes: 9

Related Questions