WA for LTIME16 CHEFD problem. seems right for all test cases i applied. please help.

Problem link

my solution link

I had done everything according to the editorial but still getting wa . I am getting right answer for the test cases i try manually :p. if you find out whats wrong in my code, then please also check why is it giving tle for subtask 2 and 3(i have applied the optimal approach given in editorial)

Thanks in advance