HELPDELHI question from codeERA

Can anyone please suggest an efficient method for solving the [HELPDELHI] 1 question from the contest codeERA? I tried solving it but it gives WA. I made a lot of if-else statements, maybe I am missing something. Any help is much appreciated.
Here is my solution which gave WA. IDEONE LINK