Affirm interview question

Difficult algorithmic question. Could not choose programming language.