Solution working for all cases but throwing 'time limit exceeded' on SPOJ