Problem :SPOJ-KGSS

My approach: I have implemented a segment tree for finding max in `[l,r]`

. Whenever any query is asked I find out the maximum element in `[l,r]`

and then update the segment tree by replacing the maximum element found by `-INF`

.Now, I find out the maximum element which gives me the second largest element in `[l,r]`

.At last, I update the first largest back to its initial value.

My code:

I am getting TLE. How can I optimize the updation part?