Post

2868 Continuous Subarrays

2868 Continuous Subarrays

Continuous Subarrays image

You are given a 0-indexed integer array nums. A subarray of nums is called continuous if:

1
Let i, i + 1, ..., j be the indices in the subarray. Then, for each pair of indices i <= i1, i2 <= j, 0 <= |nums[i1] - nums[i2]| <= 2.

Return the total number of continuous subarrays.

A subarray is a contiguous non-empty sequence of elements within an array.

 

Example 1:

1
2
3
4
5
6
7
8
9
10
11
**Input:** nums = [5,4,2,4]
**Output:** 8
**Explanation:** 
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.

 

Example 2:

1
2
3
4
5
6
7
8
9
**Input:** nums = [1,2,3]
**Output:** 6
**Explanation:** 
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.

 

Constraints:

1
2
1 <= nums.length <= 105
1 <= nums[i] <= 109
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45


class Solution:
    def continuousSubarrays(self, nums: List[int]) -> int:
        
        left = 0
        right = 0
        arr = {}
        result = 0



        def valid_range(n, arr):
            
            if len(arr) == 0:
                arr[n] = 1
                return True
            #print(arr1, arr1[0], arr1[-1])
            if max(arr.keys()) - n <= 2 and  n - min(arr.keys()) <= 2:
                if n in arr:
                    arr[n] += 1
                else:
                    arr[n] = 1
                return True
            return False 

        while(left < len(nums) and right < len(nums)):
            #print(left, right, arr)
            if valid_range(nums[right], arr):
                result += right - left + 1
                right += 1
            else:
                #result += add(right - left)
                #print(nums[left], arr.index(nums[left]))
                arr[nums[left]] -= 1
                if arr[nums[left]] == 0:
                    del arr[nums[left]]
                left += 1
        #print(arr, left, right)
        #result += add(right - left)
        return result



This post is licensed under CC BY 4.0 by the author.