Grand Temple timelimit

I passed testcase#2 and testcase#3 but i am exceeding my time limit for testcase#1. How do I overcome that?

u r using O(n^2 approach
try to optimize it it can be done in 0 n