Here is my solution for the same it is approx same but i have used one condition
https://www.codechef.com/viewsolution/30914245