查找js中的最大/最小和.为什么会失败呢?



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);
}

我从hackerrank得到这个,显然它没有通过某些测试用例,但我必须支付5"hackerrank";要了解为什么

我的简单代码

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);
}

try this

let n = prompt('Enter your number:');
let number = [];
for (i = 0; i < n; i++) {
number.push(Number(prompt('Enter #' + i + 'number:')));
}
let sum = 0;
const max = Math.max.apply(null, number);
const min = Math.min.apply(null, number);
for (i = 0; i < n; i++) {
sum += number[i]
}
let average = sum / n;
console.log(`max is ${max}`);
console.log(`min is ${min}`);
console.log(`average is ${average}`);

所有的整数都应该是唯一的吗?如果不是,那么如果有最大值和最小值的重复,这可能就行不通了?

例如[2,2,3,5,5]

所以,我只是得到了这个问题,了解它应该做什么。你需要做的是在一个整数数组中找到4个最大的值并求和,也需要找到4个最小的值并求和。(hackerrank链接:https://www.hackerrank.com/challenges/mini-max-sum/problem)

我将在下面的代码中添加注释,以便您可以理解

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}`);
}

现在,在你创建一个新问题之前,给你一些提示。

  1. 创建最大的细节,例如,你可以在发送代码之前更好地解释问题。
  2. 试着解释一下你对这个问题的理解和你想做的事情。我想你只是误解了问题的要求。

我希望我能帮助你。你可以留下任何评论,如果有什么是难以理解的,我会尽力帮助你。祝大家编程愉快!:)

最新更新