JavaScript求数组最大/最小和:为何这段代码无法通过部分测试用例?
miniMaxSum Function for HackerRank Let's break down why your current code is failing some test cases and how to fix it.
The Core Issue in Your Code
Your approach assumes there's only one occurrence of the maximum and minimum values in the array, which isn't always the case. Here's the problem:
- If the array has multiple instances of the maximum value (e.g.,
[1, 2, 3, 4, 4]), your code excludes all 4s from theminsumcalculation. The correct minimum sum should exclude just one 4, not both. - Similarly, if there are multiple minimum values (e.g.,
[1, 1, 2, 3, 4]), your code excludes all 1s from themaxsumcalculation, when you only need to exclude one.
Another minor (but less impactful) issue is using for...in to iterate over an array. for...in is designed for object properties, not arrays—while it works here, it's better practice to use for...of or array methods for array iteration.
A Simplified, Correct Solution
Instead of looping and checking each element, you can calculate the total sum of the array first. Then:
- The minimum sum is total sum minus the largest element (exclude one largest element to get the smallest possible 4-number sum)
- The maximum sum is total sum minus the smallest element (exclude one smallest element to get the largest possible 4-number sum)
Here's the revised code:
function miniMaxSum(arr) { const totalSum = arr.reduce((acc, num) => acc + num, 0); const largest = Math.max(...arr); const smallest = Math.min(...arr); const minSum = totalSum - largest; const maxSum = totalSum - smallest; console.log(minSum, maxSum); }
Why This Works
This approach handles duplicate max/min values perfectly. For example:
- In
[1,2,3,4,4], total sum is 14.minSum = 14 - 4 = 10(correct, since we exclude just one 4),maxSum = 14 -1 =13(correct, exclude the 1). - In
[1,1,2,3,4], total sum is 11.minSum =11-4=7,maxSum=11-1=10(correct, exclude one 1 instead of both).
This method is also more efficient—it runs in O(n) time (same as your loop) but with cleaner, more readable code.
内容的提问来源于stack exchange,提问作者harmonyrhi

