I solved this problem using segment tree. For querying the two maximum numbers in a range(i,j), I called the query() function twice with different ranges. I have checked for several test cases and it is giving the correct answer but its showing WA in the judge. Please tell me where I am doing wrong. Here is the source code and the link to the problem.

Link to the problem- http://www.spoj.com/problems/KGSS/

link to the implemented code- http://ideone.com/wvoF5a

Please tell me my mistake.Thanks!!