You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript求数组最大/最小和:为何这段代码无法通过部分测试用例?

Fixing Your 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 the minsum calculation. 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 the maxsum calculation, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 20:27:30