Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 921
claudiopb Avatar asked Oct 15 '25 14:10

claudiopb


2 Answers

I think the solution should be easier:

function miniMaxSum(arr) {
    let sum = arr.reduce((a, b) => a + b);
    let maxVal = Math.max(...arr);
    let minVal = Math.min(...arr);
    console.log((sum - maxVal) + ' ' + (sum - minVal));
}
like image 191
Dheymer León Avatar answered Oct 17 '25 07:10

Dheymer León


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
like image 22
claudiopb Avatar answered Oct 17 '25 08:10

claudiopb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!