Java based solution to Hacker rank Algorithm problem, Level : Difficult