function miniMaxSum(arr) { // Write your code here let max = Math.max(...arr); let min = Math.min(...arr); let minsum = 0; let maxsum = 0; for (let x in arr) { if (arr[x] != max) { minsum += arr[x]; }; if (arr[x] != min) { maxsum += arr[x]; } }; console.log(minsum, maxsum); }Obtuve esto de hackerrank, y aparentemente falla en ciertos casos de prueba, pero tengo que pagar 5 "hackos" para saber por qué.
mi codigo sencillo
function miniMaxSum(arr) { var max = 0; var min = 0; arr.sort(); for(var i = 0;i<arr.length;i++){ if(i>0 ){ max = max + arr[i]; } if(i<4){ min = min + arr[i]; } } console.log(min + " " + max); }¿Se supone que todos los números enteros son únicos? Si no es así, ¿es posible que esto no funcione si hay duplicados de números máximos y mínimos?
Por ejemplo [2,2,3,5,5]
Entonces, acabo de entender el problema para entender lo que se supone que debe hacer. Lo que debe hacer es encontrar los 4 valores más grandes en una matriz de enteros y sumarlos, y también debe encontrar los 4 valores más pequeños y sumarlos. (enlace de hackerrank: https://www.hackerrank.com/challenges/mini-max-sum/problem )
Dejaré el código abajo con comentarios para que puedas entender
function miniMaxSum(arr) { //make a copy of the original array to calculate the max sum value let arrMax = [...arr]; //make a copy of the original array to calculate the min sum value let arrMin = [...arr]; let maxSum = 0; let minSum = 0; // We need to find the sum of the biggest/lowest 4 values for (let i = 0; i < 4; i++) { //find the index of the element with the biggest value let maxElementIndex = arrMax.findIndex(value => value === Math.max(...arrMax)); //sum the value to the max sum result maxSum += arrMax[maxElementIndex]; //remove the value from the array arrMax.splice(maxElementIndex,1); // here I am doing the same, but now to get the lowest value let minElementIndex = arrMin.findIndex(value => value === Math.min(...arrMin)); minSum += arrMin[minElementIndex]; arrMin.splice(minElementIndex,1); } console.log(`${minSum} ${maxSum}`); }Ahora, algunos consejos para usted antes de crear una nueva pregunta.
Espero que te pueda ayudar. Puedes dejar cualquier comentario si algo es difícil de entender y trataré de ayudarte. ¡Y feliz codificación! :)