DVCQ-P1

Largest and smallest together

Practice 1 of 6Divide and conquer9 tests

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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

9 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2One valueNot run
3Two valuesNot run
4All equalNot run
5Negative valuesNot run
6Six valuesNot run
7Falling, 100,000 valuesNot run
8Random, 100,000 valuesNot run
9Random, 99,999 valuesNot run