You are given a 0-indexed integer array nums
. A subarray of nums
is called continuous if it satisfies the following condition:
i, i + 1, ..., j
be the indices of the subarray. Then, for each pair of indices i1
and i2
such that i <= i1, i2 <= j
, the absolute difference between the elements at those indices is at most 2:0 <= |nums[i1] - nums[i2]| <= 2
.Your task is to return the total number of continuous subarrays present in nums
.
Input:
nums = [5, 4, 2, 4]
Output:
8
Explanation:
Continuous subarrays are:
[5]
, [4]
, [2]
, [4]
(4 subarrays).[5, 4]
, [4, 2]
, [2, 4]
(3 subarrays).[4, 2, 4]
(1 subarray).There are no valid subarrays of size 4.
Total continuous subarrays = 4 + 3 + 1 = 8.
Input:
nums = [1, 2, 3]
Output:
6
Explanation:
Continuous subarrays are:
[1]
, [2]
, [3]
(3 subarrays).[1, 2]
, [2, 3]
(2 subarrays).[1, 2, 3]
(1 subarray).Total continuous subarrays = 3 + 2 + 1 = 6.
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
nums
.0 <= |nums[i1] - nums[i2]| <= 2
is satisfied for all pairs within the subarray.O(n^3)
or O(n^2)
(with optimizations).A HashMap
is used to track the frequency of elements in the current window. This helps verify whether the window is valid (i.e., the difference condition is satisfied).
For each new element added to the window:
p1
to i
) is valid.For each valid subarray ending at index i
, the code calculates the total number of subarrays that can be formed starting between p1
(start of the window) and i
:
(i - p1 + 1)
.If the subarray becomes invalid, the start of the window (p1
) is moved forward until the subarray becomes valid again.
The total count of valid subarrays is accumulated as the window slides through the entire array.
This problem requires careful handling of large inputs while ensuring efficiency. An efficient implementation with the sliding window approach is most suitable.
Loading component...
Loading component...
Main Function is not defined.
private int getcount( int number , Map<Integer , Integer> mp){
int ans = mp.getOrDefault(number , 0 ) + mp.getOrDefault(number -1 , 0 ) + mp.getOrDefault(number+1 , 0 );
ans = ans + mp.getOrDefault(number- 2 , 0 ) + mp.getOrDefault(number+ 2 , 0 );
return ans;
}//function end
public static long continuousSubarrays(int[] nums){
int n = nums.length
int p1 = 0;
long count =0;
Map<Integer, Integer> mp = new HashMap<>();
for(int i =0; i < n; i++){
mp.put(nums[i] , mp.getOrDefault(nums[i],0) +1);
int count_value = getcount( nums[i] , mp);
while((i - p1 + 1) > count_value){
mp.put(nums[p1] , mp.get(nums[p1]) - 1);
p1++;
count_value = getcount(nums[i] , mp );
}
count += ( i - p1 + 1 );
}
return count;
}//function end