Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

330
Visualizações
Javascript Mini-Max Sum HackerRank problem returns wrong sum?

I've been pulling my hair out trying to figure out what I'm doing wrong. In the HackerRank problem, Mini-Max Sum the question is to find the sum of part of an array of 5 numbers. In the example they give you, they show you arr = [1,2,3,4,5] the minimum sum would be 1+2+3+4 = 10 and the maximum sum would be 2+3+4+5 = 14

I'm still new so solving the problem is still sometimes a challenge for me. I came up with this for my first solution:

function minMax(arr){

   console.log(arr, 'this is our arr')

   var baseSum = 0
   var minSum = 0
   var maxSum = 0
   var i = null


   for(i=1;i<4;i++){
     baseSum += arr[i]
   }

   console.log(baseSum, 'this is baseSum')
   console.log(minSum = baseSum + arr[0], maxSum = baseSum + arr[4])
}

const numArr = [7, 69, 2, 221, 8974]

minMax(numArr)

My thinking is that I could grab the numbers that are consistent between the two variables, grab the first and last number of the array and add those up to get the result. It passed one test but it fails at the listed values at numArr, If I add up those last 4 numbers, I get 9266 but the expected value is 9271.

I spent some time trying to think of a way to refactor it, I knew it wasn't great to begin with but I'm trying!

I came up with this -

function minMax(arr){
  if (arr.length > 5){
    return "Too long"
  }

  var minArr = arr.slice(0,4)
  var maxArr = arr.slice(1,5)

  minSum = 0
  maxSum = 0

  for (i=0; i < minArr.length;i++){
    minSum += minArr[i]
  }

  for (x=0; x < maxArr.length; x++){
    maxSum += maxArr[x]
  }

  console.log(minSum, maxSum)
}

But it returned the exact same thing as before. So I'm either, not understanding the question (probably what's happening) or the sum is wrong in their expected value. I even just grabbed a calculator and I'm getting 9266 so I don't get what I'm doing wrong.

Has anyone run into this and do they have any ideas what is going on?

UPDATE

No surprise to myself, I read the question wrong. You are supposed to sort the actual array before you get the sum. They don't really state in the question so it's poorly worded imo lol but this is ultimately all I did to get the correct value in case anyone is wondering.

if (arr.length > 5){
    return "Too long"
  }



  arr.sort(function(a, b) {
  return a - b;
  });

  var minArr = arr.slice(0,4)
  var maxArr = arr.slice(1,5)

  var minSum = 0
  var maxSum = 0
  var i = null
  

  for (i=0;i<minArr.length;i++){
    minSum += minArr[i]
  } 

  for (i=0;i<maxArr.length;i++){
    maxSum += maxArr[i]
  }

  console.log(minSum, maxSum)

}


const numArr = [7, 69, 2, 221, 8974]

minMax(numArr)

This obviously sums up different values so you'll get the correct answer!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

In the question, It is not specified whether the input array will be sorted or not, So the only thing that you are missing is to sort the array in descending order.

1) You can first sort the array in ascending order

const clone = [...arr].sort((a, b) => a - b);

2) the take first four sum.

const minSum = arr.slice(0, 4).reduce(sum, 0);

3) also take the last four sum

const maxSum = arr.slice(1).reduce(sum, 0);

function minMax(arr) {
  const clone = [...arr].sort((a, b) => a - b);
  const sum = (acc, curr) => acc + curr;
  const minSum = clone.slice(0, 4).reduce(sum, 0);
  const maxSum = clone.slice(1).reduce(sum, 0);
  console.log(minSum, maxSum);
}

const numArr = [7, 69, 2, 221, 8974];

minMax(numArr);

about 4 years ago · Juan Pablo Isaza Relatório

0

To continue having something semi-MinMax oriented. I would suggest sorting as a separate step. Then you can have two pointers in the array that move concurrently through the array to count the minimum and maximum:

function rank(arr, low, high) {
  if (arr.length > 5) {
    console.log("Too long");
    return;
  }

  // we reached the fourth value, so we stop
  if (high == 1)
    return [arr[low], arr[high]];

  // continue calculating at further depth
  let minMaxRecur = rank(arr, low + 1, high - 1);
  return [arr[low] + minMaxRecur[0], arr[high] + minMaxRecur[1]];
}

let initialArray = [7, 69, 2, 221, 8974];
initialArray.sort((a, b) => a - b); // sort first

console.log(rank(initialArray, 0, 4));

This uses a recursive algorithm to count through the array, but this could of course be much simpler with a single loop that goes through the array like:

function rankLoop(arr) {

  let min = 0, max = 0;
  for (let i = 0; i < 4; i++) {
      min += arr[i];
      max += arr[4 - i];
  }
  
  return [min, max];
}

console.log(rankLoop([2, 7, 69, 221, 8974], 0, 4));

This again assumes that the array coming in it sorted, which can be seen in my first code snippet. Either of these works with the same time complexity.

about 4 years ago · Juan Pablo Isaza Relatório

0

in Python :

def miniMaxSum(arr):
    arr.sort()
    hold = [None]*int(len(arr)-3)

    for i in range(0,len(arr)-3):
        temp = 0

        for j in range(i,i+4):
            temp = temp + arr[j]
        hold[i] = temp
    
    print(hold[0],hold[-1])
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda