思考题 in ancient Chinese

Orange Boy Can You Solve It Out? / 神犇,解乎?

令和元年九月二十一日,余与神犇同饮,乐也。见月色空明,开而无雨,犇曰「如此宴酣之乐,何不以卵玩之以陶冶情操?」,杂然相许。

但见数卵,神犇摆之成堆。共N堆,i堆卵耳。犇问之「汝能寻多少L,R整数对,使期间有序,而总亦有序乎?」。难矣,难矣,余思之数日,仍未解!君,解乎?

On 2019 Sept 21, I took part in AGC038 with Orange Boy. Happily, I went out to see the moon, round and clear, the sky, pure and sunny, so Orange Boy said:"Today is such a happy day, why don't we play pebbles?" Everyone agrees.

So there are N piles of pebbles, the i-th pile contains Ai pebbles. Orange Boy asks me:"How many interval L,R can you find, so that after sorting the elements from L to R, the whole array will become sorted too?" That's hard, so can you solve it?

Example / 例

A={1,3,2,4}
Out:4
Explain:
L=1,R=1, bad
L=1,R=2, bad
L=1,R=3, ok
L=1,R=4, ok
L=2,R=2, bad
L=2,R=3 ok
L=2,R=4 ok
L=3,R=3 bad
L=3,R=4 bad

Constriants / 规

Subtask 1(50%):n<=1000
Subtask 2(50%):N<=1000000

Orange Boy Loves Ancient Chinese, so he solved it.