Sum excluding one element in JavaScript

In JavaScript, when you need to find the minimum and maximum possible sums by excluding exactly one element from an array, you can solve this efficiently using a single loop approach.

The key insight is that to get the minimum sum (excluding one element), you remove the largest element. To get the maximum sum (excluding one element), you remove the smallest element.

Problem Statement

Given an array of integers, return an array with two values:

  • First integer: smallest possible sum excluding any one element

  • Second integer: greatest possible sum excluding any one element

For example, with the array [12, 1, 4, 8, 5]:

Input: [12, 1, 4, 8, 5]
Output: [18, 29]

The output [18, 29] comes from excluding 12 (largest) for minimum sum and excluding 1 (smallest) for maximum sum.

Solution Approach

The algorithm works by tracking three values in a single loop:

  • Total sum of all elements

  • Maximum element (to subtract for minimum sum)

  • Minimum element (to subtract for maximum sum)

Example Implementation

const arr = [12, 1, 4, 8, 5];

const findExtremeNumbers = (arr = []) => {
    let sum = 0;
    let min = Infinity;
    let max = -Infinity;
    
    for(let i = 0; i < arr.length; i++){
        const curr = arr[i];
        sum += curr;
        
        if(curr > max){
            max = curr;
        }
        if(curr < min){
            min = curr;
        }
    }
    
    return [sum - max, sum - min];
};

console.log(findExtremeNumbers(arr));
[18, 29]

How It Works

The function processes each element once:

  1. Sum calculation: sum += curr adds each element to the total

  2. Max tracking: max stores the largest element found

  3. Min tracking: min stores the smallest element found

  4. Return values: [sum - max, sum - min] gives the desired result

Testing with Different Arrays

// Test with different arrays
console.log(findExtremeNumbers([5, 2, 8, 1]));  // [11, 15]
console.log(findExtremeNumbers([10, 20, 30]));   // [30, 50]
console.log(findExtremeNumbers([7, 7, 7]));      // [14, 14]
[11, 15]
[30, 50]
[14, 14]

Key Points

  • Time complexity: O(n) - single loop through the array

  • Space complexity: O(1) - only storing three variables

  • Works with positive, negative, and duplicate numbers

  • Efficiently solves the problem in one pass

Conclusion

This single-loop approach efficiently finds both extreme sums by tracking the total sum alongside the minimum and maximum elements. The solution is optimal with O(n) time complexity and demonstrates how mathematical insight can simplify array processing problems.

Updated on: 2026-03-15T23:19:00+05:30

800 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements