The problem
Return the pair (largest, smallest) of a list of at least one number. Finding each one separately takes 2n − 2 comparisons. Do it with at most 3 * n // 2 comparisons, where n is the number of values (3n/2, rounded down).
max_min([3, 7, 1, 9, 4]) # (9, 1), at most 7 comparisons
max_min([5]) # (5, 5), no comparisons needed
The tests pass the values as special number objects that count every comparison made with them (<, <=, >, >=; == is not counted). They behave like normal numbers, and max() and min() count too. Return the values you were given, not copies made with int().
Limits
- Up to 100,000 values, in any order. The limit on comparisons holds for every n, odd or even.
Builds on DVCQ-1 The pattern.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | One value | Not run | |
| 3 | Two values | Not run | |
| 4 | All equal | Not run | |
| 5 | Negative values | Not run | |
| 6 | Six values | Not run | |
| 7 | Falling, 100,000 values | Not run | |
| 8 | Random, 100,000 values | Not run | |
| 9 | Random, 99,999 values | Not run |