<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A subarray of <code>nums</code> is called <strong>continuous</strong> if:</p>

<ul>
	<li>Let <code>i</code>, <code>i + 1</code>, ..., <code>j</code><sub> </sub>be the indices in the subarray. Then, for each pair of indices <code>i &lt;= i<sub>1</sub>, i<sub>2</sub> &lt;= j</code>, <code><font face="monospace">0 &lt;=</font> |nums[i<sub>1</sub>] - nums[i<sub>2</sub>]| &lt;= 2</code>.</li>
</ul>

<p>Return <em>the total number of <strong>continuous</strong> subarrays.</em></p>

<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [5,4,2,4]
<strong>Output:</strong> 8
<strong>Explanation:</strong> 
Continuous subarray of size 1: [5], [4], [2], [4].
Continuous subarray of size 2: [5,4], [4,2], [2,4].
Continuous subarray of size 3: [4,2,4].
Thereare no subarrys of size 4.
Total continuous subarrays = 4 + 3 + 1 = 8.
It can be shown that there are no more continuous subarrays.
</pre>

<p>&nbsp;</p>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,3]
<strong>Output:</strong> 6
<strong>Explanation:</strong> 
Continuous subarray of size 1: [1], [2], [3].
Continuous subarray of size 2: [1,2], [2,3].
Continuous subarray of size 3: [1,2,3].
Total continuous subarrays = 3 + 2 + 1 = 6.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>
</ul>

from sortedcontainers import SortedList
class Solution:
    def continuousSubarrays(self, nums: List[int]) -> int:
        '''
        min <= max <= min + 2

        '''
        # minheap = []
        # maxheap = []
        minheap = SortedList()
        maxheap = SortedList()
        i,j = 0,0
        count = 0
        n = len(nums)
        while j < n:
            minheap.add((nums[j],j))
            maxheap.add((-nums[j],j))
            # heapq.heappush(minheap,(nums[j], j))
            # heapq.heappush(maxheap,(-nums[j],j))

            while i < j and minheap and maxheap and -maxheap[0][0] - minheap[0][0] > 2:
                idx1 = minheap[0][1]
                idx2 = maxheap[0][1]
                if idx1 < idx2:
                    i = idx1+1
                    minheap.discard((nums[idx1], idx1))
                    maxheap.discard((-nums[idx1], idx1))
                else:
                    i = idx2 + 1
                    minheap.discard((nums[idx2], idx2))
                    maxheap.discard((-nums[idx2], idx2))

            count += (j - i) + 1
            j+=1
        return count

        '''
        i = 1
        j = 3
        min = [(2,2)(4,1),(4,3)]
        max = [(-4,1),(-4,3),(-2,2)]
        count = 1 + 2 + 2 + 3
        
        
        '''
44300