Skip to content
ExamSpine

Lesson 5.9 · Write it

Largest minus smallest

A functionPython or Java11 tests, 7 of them hidden

On a phone? Put the lines in order instead

Write a function that returns the largest value in a list (an array in Java) of whole numbers minus the smallest value in it.

  1. The list always has at least one value, and has at most 20 values.
  2. Every value is between -1000 and 1000, and the values can be negative.
  3. Write the loop yourself. The shortcuts listed with this question are not allowed.

Only the number your function returns is checked.

def spread(values: list[int]) -> int

You cannot use these in this question:

  • max()
  • min()
  • sorted()
  • .sort()
  • import heapq
  • import statistics

Some exam questions ask you to find the largest or smallest yourself, so practise the loop. The shortcuts listed are not allowed.

Examples

Your function is tested on 11 cases: the 4 examples below, and 7 hidden ones that check the rules above.

  • spread([3, 8, 5]) should return 5: 8 is the largest and 3 the smallest, so 8 - 3
  • spread([4]) should return 0: one value is both the largest and the smallest (rule 1)
  • spread([-6, -2, -9]) should return 7: all negative: -2 - (-9) is 7 (rule 2)
  • spread([10, 1, 7]) should return 9: the largest is first, and a later value is smaller than the first but not the smallest

public static int spread(int[] values)

Checking whether Java answers can run here.

You cannot use these in this question:

  • Math.max()
  • Math.min()
  • Arrays.sort()
  • Arrays.parallelSort()
  • Arrays.stream()
  • Collections.max()
  • Collections.min()
  • IntStream.of()
  • .sort()
  • .stream()
  • .max()
  • .min()
  • .summaryStatistics()
  • import java.util.stream

Some exam questions ask you to find the largest or smallest yourself, so practise the loop. The shortcuts listed are not allowed.

Examples

Your function is tested on 11 cases: the 4 examples below, and 7 hidden ones that check the rules above.

  • spread(new int[]{3, 8, 5}) should return 5: 8 is the largest and 3 the smallest, so 8 - 3
  • spread(new int[]{4}) should return 0: one value is both the largest and the smallest (rule 1)
  • spread(new int[]{-6, -2, -9}) should return 7: all negative: -2 - (-9) is 7 (rule 2)
  • spread(new int[]{10, 1, 7}) should return 9: the largest is first, and a later value is smaller than the first but not the smallest
solution.pySolution.java