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.
- The list always has at least one value, and has at most 20 values.
- Every value is between -1000 and 1000, and the values can be negative.
- 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)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.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