Example test cases solved but 'time limit exceeded' in a JS code

This is my first problem in Codechef and my logic solves all the example test cases but fails in the time limit. Can someone provide a suggestion on how to improvise?

https://www.codechef.com/viewsolution/27986667