Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

676
Views
Hackerrank Mini-Max Sum - Doesn't pass test case

I am working on Hackerrank challenge Mini-Max Sum:

Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.

Example

arr = [1, 3, 5, 7, 9]

The minimum sum is 1 + 3 + 5 + 7 = 16 and the maximum sum is 3 + 5 + 7 + 9 = 24.

The function prints

16 24

I submitted the below code, but it doesn't pass one sample test case. Is there anything wrong in my code?

function miniMaxSum(arr) {
    let set = [...new Set(arr)];
    const MIN = set.filter((num) => num !== Math.max(...set)).reduce((sum, num) => sum + num);
    const MAX = set.filter((num) => num !== Math.min(...set)).reduce((sum, num) => sum + num);
    console.log(MIN + ' ' + MAX);
}

The error is a "Runtime Error"

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Some issues:

  • A problem will occur when all 5 input values are equal. In that case the filter call will return an empty array, on which reduce is called. As reduce is called without the "initial value" argument, a run-time error will occur.
  • There is no indication in the challenge that duplicate values should only be accounted for once in the sum. So if the input does contain duplicate values, this will not always produce correct results.

Not a problem, but:

  • Calculating the min/max in each iteration of the filter callback is not efficient -- it will be the same result every time, so better calculate this only once.

Here is a working solution that takes the above points into consideration:

function miniMaxSum(arr) {
    const sum = arr.reduce((a, b) => a + b);
    const min = sum - Math.max(...arr);
    const max = sum - Math.min(...arr);
    console.log(`${min} ${max}`);
}
about 4 years ago · Juan Pablo Isaza Report

0

@Trincot already explained the error in all details. Nothing to be added there.

Here is yet another way of doing it by avoiding redundant calculations:

function mms(arr) { 
  const [a,...ar]=arr;
  let [min,max,sum]=[a,a,a];
  ar.forEach(c=>{
    if(c<min) min=c
    else if (c>max) max=c
    sum+=c
  });
  return `${sum-max} ${sum-min}`
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!