Affirm Interview Question

Difficult algorithmic question. Could not choose programming language.