Learn > Higher Computing Science > Higher Python Course > 3. Find maximum / minimum

Find maximum / minimum

The Find Maximum / Minimum algorithm is used to find the largest or smallest value in an array. It works by starting with the first item in the array as the current maximum (or minimum). The loop then begins at position 1 (the second item), because the first item has already been stored as the starting value. If a bigger (or smaller) value is found, it replaces the current maximum (or minimum).

If two or more values in the array are equal to the maximum (or minimum), the algorithm will only identify the first occurrence it finds. This is because once a match is found, the stored maximum (or minimum) is not updated unless a strictly bigger (or smaller) value appears later in the array.

Key points

  • Choose the first item in the array as the starting value.
  • Start the loop from position 1 because position 0 is already being used as the starting value.
  • If two values are tied for maximum/minimum, the first occurrence will be the one found.

Example Code

scores = [12, 18, 15, 20, 9, 14]

maximum = scores[0]

for i in range(1, len(scores)):
    if scores[i] > maximum:
        maximum = scores[i]

print("The maximum value is:", maximum)
scores = [12, 18, 15, 20, 9, 14]

minimum = scores[0]

for i in range(1, len(scores)):
    if scores[i] < minimum:
        minimum = scores[i]

print("The minimum value is:", minimum)
# Array storing scores
scores = [12, 18, 15, 20, 9, 14]

# Set the first value in the array as the current maximum
maximum = scores[0]

# Loop through positions 1 to the end of the array
for i in range(1, len(scores)):
    # If the value at the current position is greater than the current maximum
    if scores[i] > maximum:
        # Update the maximum to this new value
        maximum = scores[i]

# Output the maximum value found
print("The maximum value is:", maximum)