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!