Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Sum Except Max & Min

Sum list entries after excluding one maximum and one minimum. Students trace totals and see why repeated extreme values are not all removed by subtraction.

AdvancedPhase 4 - Level 5: Logical & AppliedExample 6 of 14
sum-except-max-min.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7# Sum except max and min
8if len(arr) <= 2:
9 print("Sum: 0 (array too small)")
10else:
11 max_val = max(arr)
12 min_val = min(arr)
13 total_sum = sum(arr)
14 result = total_sum - max_val - min_val
15 print(f"Sum (excluding max and min): {result}")

Output

Enter array size: 5
Element 1: 10
Element 2: 5
Element 3: 20
Element 4: 3
Element 5: 15
Sum (excluding max and min): 30

In this one

  • Subtract selected occurrences
  • Keep repeated extremes honestly
  • Handle short inputs

How it works

  1. 1

    Return the short-list zero message when appropriate.

  2. 2

    Calculate total, maximum, and minimum.

  3. 3

    Subtract one occurrence of each extreme from total.

Edge cases

Are all repeated maxima removed?

Are all repeated maxima removed?

No. Only one maximum is subtracted.

What if all four entries are two?

What if all four entries are two?

The result is four after subtracting two occurrences.

What's going on

The code computes the complete sum, then subtracts max_val once and min_val once. It does not filter out every occurrence of those values.

For [1, 1, 5, 5], the result is six, leaving one of each extreme in the arithmetic. Lists with two or fewer entries return zero through a separate branch. This is an exclusion by occurrence count, not by distinct value.

Are all repeated maxima removed? No. Only one maximum is subtracted.

What if all four entries are two? The result is four after subtracting two occurrences.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does the short-list branch report?

Pick an answer to check it.

Question 2

Are all repeated maxima removed?

Pick an answer to check it.

Questions people ask

Are all repeated maxima removed?

No. Only one maximum is subtracted.

What if all four entries are two?

The result is four after subtracting two occurrences.

What does the short-list branch report?

Zero.