Issue with the code

In the above code in line “while(j<n)”
it will lead j to increase upto 3 instead of two and for that case the formula given is not working.

this formula would work if the value of j was 2 but while dry running the code , the value of j becomes 3 , for which the code doesn’t work

you are right
it should be ans += ((j - i) * (j - i + 1))/2;