J.P. Morgan Interview Question

How to solve the coding problem.