J.P. Morgan interview question

Have to solve hackerrank. It is a tough interview.