Problem overview
The function trimmedTotal receives a slice of integers, nums, with 3 to 100 numbers, and returns their sum without one smallest and one largest value. It is how some contests score: each judge gives a score, and the lowest and the highest are dropped so that one judge can't decide alone.
Only one copy of each extreme is dropped. If the smallest value appears twice, the other copy still counts, and the same goes for the largest.
For [7, 9, 6, 8, 10] the smallest is 6 and the largest is 10, so the answer is 7 + 9 + 8 = 24. For [5, 1, 5, 9, 1] one of the two 1s and the 9 are dropped, leaving 5 + 5 + 1 = 11. For [-4, 3, -2] only -2 is left.
Approach: add everything, then subtract two numbers
Instead of removing items from the slice, work with totals. Add all the numbers, then subtract the smallest value once and the largest value once. Subtracting a value once removes exactly one copy of it from the sum, so repeated extremes are handled without any special case.
Go has no function that sums a slice, so a loop does it. The smallest and largest come from slices.Min and slices.Max, which look at a whole slice. Both panic on an empty slice, but the lesson guarantees at least three numbers.
Step by step
- Create
totalwith:=and set it to 0. - Loop with
for _, num := range nums, dropping the index with an underscore. - Add each number with
total += num. - Find the smallest with
slices.Min(nums)and store it insmallest. - Find the largest with
slices.Max(nums)and store it inlargest. - Return
total - smallest - largest.
The solution in Go
func trimmedTotal(nums []int) int {
total := 0
for _, num := range nums {
total += num
}
smallest := slices.Min(nums)
largest := slices.Max(nums)
return total - smallest - largest
}
The slices package has been part of Go's standard library since Go 1.21. In a file of your own you import it with import "slices"; the lesson's editor already has what it needs. The function never changes nums, so the caller's slice stays as it was.
Testing
Running the function on the statement's examples, plus the case where every number is equal, prints:
[7 9 6 8 10] 24
[5 1 5 9 1] 11
[-4 3 -2] -2
[3 3 3] 3
In [3 3 3] the smallest and the largest are both 3, but they are still two separate subtractions: one copy is dropped for each role, so one 3 remains.
Edge cases and common mistakes
- Dropping every copy. Skipping all numbers equal to the smallest or the largest over-trims. On
[5, 1, 5, 9, 1]that approach adds only 5 + 5 = 10 instead of 11. - Subtracting too early. The subtraction belongs after the loop, once
totalholds the full sum. - Negative numbers. Nothing special is needed. Subtracting a negative smallest value adds to the total, which is correct: in
[-4, 3, -2]the total is -3, and -3 - (-4) - 3 = -2. - Sorting the slice just to drop the ends. It works, but it is more code, and it reorders the caller's data.
