I am trying to learn Mo’s algorithm and am trying to solve various problems with it but as of now failing badly. The problem I am trying is Powerful Arrays from Codeforces. I am pretty sure the query is sorted correctly but its still giving me TLE verdict. How can I optimize it to run quicker. The submission in question: Submission.
your code is exactly what I did. For test case #6, its taking Time: 2246 ms in your case and for me its giving TLE. I am doing some optimizations, lets see.
Nope ,it should start from right. (I dont know if its in ur case as it depends on question) Assume that the first query is (2,4) so by moving left pointer first u actually remove the things that were never added which can cause problems in most of sums.Thats why we shoupd move right ,then left.
It’s not about left or right, the add operations should be done before the remove operations. However for this problem the order does not matter because the math works out.