Simple Algorithm, Simple Solution

Joseph Kniskern
2 min readJan 14, 2021

--

Given an array of integers return the minimum and maximum possible sum of all but one of the integers.

It sounds vague to me, like most algorithms, but what’s going on here?

Well we need a sum of all the integers except one. That means that we can find the minimal sum by adding every number and exclude the largest number. The maximum sum can be found by doing the same, save for the largest number, and instead we exclude the smallest number.

The roundabout way would be to find the largest and smallest numbers using Math.max and Math.min, and saving those as variables. Then we could loop through the array and increase and maxSum or minSum if the numbers aren’t the largest or smallest within the array. It might look something like this:

That’s a lot of work for a pretty simple algorithms. So let’s take it apart a bit.

We know that is we sort the array the smallest and largest numbers will be at the first position and last position in the array. So we don’t even need to loop! We can also slice, taking out those numbers we don’t want, and reduce to sum. Like this:

Thats better!

--

--

No responses yet