Search code examples
javascriptalgorithm

JavaScript Mini-Max Sum - Challenge from HackerRank website


Here is the Challenge:

https://www.hackerrank.com/challenges/mini-max-sum/problem

Despite my answer is returning the same number that matches the expected result, I have done something wrong because my answer has been rejected. How can I solve it?

Here is the solution I had tried:

function miniMaxSum(arr) {   

  var arrClone1 = arr.slice() 
  var arrClone2 = arr.slice() 

  var arrMinor = arrClone1.sort(function(a, b){return a - b;})
  arrMinor.pop()

  var arrMajor = arrClone2.sort(function(a, b){return b - a;})
  arrMajor.pop()

  function getSum(a, b) {
    return a + b;
  }

  var result1 = arrMinor.reduce(getSum) 
  var result2 = arrMajor.reduce(getSum)    

  console.log(`${result1} ${result2}`) // it is returning: 10 14 

Solution

  • I found the answer. I noticed that it was mandatory to name the function argument as 'input' instead of 'arr'. That's why the answer was rejected by the HackerRank platform despite the code returned the right result in my editor, NOT in the HackerRank platform. If you do this simply adjustment, it works in the HackerRank platform too.

    Just like that:

    function miniMaxSum(input) {   //'input' NOT 'arr'    
      var arrClone1 = input.slice()   //'input' NOT 'arr'
      var arrClone2 = input.slice()   //'input' NOT 'arr'
    
    //... rest of the code omitted