Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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:
Sum calculation:
sum += curradds each element to the totalMax tracking:
maxstores the largest element foundMin tracking:
minstores the smallest element foundReturn 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.
