DYNP-P2

Exchanging a coin

Practice 2 of 9Dynamic programming9 tests

The problem

A bank will exchange a coin with the number n on it for three coins: n // 2, n // 3 and n // 4 (each divided and rounded down). You can also sell any coin for as many rupees as its number. You may exchange the new coins again, as often as you like. Return the most rupees you can end up with.

exchange(12)   # 13: 12 -> 6, 4, 3; sell all three
exchange(11)   # 11: 5 + 3 + 2 = 10, so sell it
exchange(24)   # 27

Limits

  • n is from 0 to 10¹⁸ (a 1 followed by 18 zeros). A list with one entry for every number up to n would never fit in memory.
  • The tests call your function many times in a row, with different values of n.

Builds on DYNP-2 Memoisation.

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
2ZeroNot run
3Selling is betterNot run
4TwiceNot run
5Every n below 40Not run
6One millionNot run
7One billionNot run
810¹²Not run
910¹⁸Not run