BITS-P5

The closest subset sum

Practice 5 of 5Bit manipulation13 tests

The problem

Choose some of the numbers in the list a (any of them, or none). Return how close their sum can get to target: the smallest possible value of abs(sum - target). The empty choice has sum 0.

closest_sum([3, 9, 14], 20)    # 3: 17 or 23
closest_sum([3, 9, 14], 23)    # 0: 9 + 14
closest_sum([-7, 4, 10], 2)    # 1: -7 + 10 = 3
closest_sum([], 5)             # 5

Limits

  • a has up to 36 numbers, each from −10¹² to 10¹² (minus and plus a million million). target is a whole number of the same size or larger.
  • 36 numbers have 2³⁶, about 69 billion, subsets: listing them all is far too slow. The biggest tests have 5 seconds each.

Builds on BITS-5 Subsets as bitmasks.

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.

13 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2An exact hitNot run
3No itemsNot run
4Target 0Not run
5Negative valuesNot run
6One itemNot run
7Equal itemsNot run
816 small valuesNot run
920 large valuesNot run
1030 valuesNot run
1135 valuesNot run
1236 valuesNot run
13Far above every sumNot run