-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0091_P2444_Count_Subarrays_With_Fixed_Bounds.cpp
41 lines (37 loc) · 1.29 KB
/
0091_P2444_Count_Subarrays_With_Fixed_Bounds.cpp
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
/*
Day: 91
Problem Number: 2444 (https://leetcode.com/problems/count-subarrays-with-fixed-bounds)
Date: 31-03-2024
Description:
You are given an integer array nums and two integers minK and maxK.
A fixed-bound subarray of nums is a subarray that satisfies the following conditions:
* The minimum value in the subarray is equal to minK.
* The maximum value in the subarray is equal to maxK.
Return the number of fixed-bound subarrays.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [1,3,5,2,7,5], minK = 1, maxK = 5
Output: 2
Explanation: The fixed-bound subarrays are [1,3,5] and [1,3,5,2].
Example 2:
Input: nums = [1,1,1,1], minK = 1, maxK = 1
Output: 10
Explanation: Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.
Constraints:
* 2 <= nums.length <= 10^5
* 1 <= nums[i], minK, maxK <= 10^6
Code: */
class Solution {
public:
long long countSubarrays(vector<int>& nums, int minK, int maxK) {
long long ans = 0;
int j1 = -1, j2 = -1, k = -1;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] < minK || nums[i] > maxK) k = i;
if (nums[i] == minK) j1 = i;
if (nums[i] == maxK) j2 = i;
ans += max(0, min(j1, j2) - k);
}
return ans;
}
};