Skip to content

Commit f8ad168

Browse files
committed
new soln
1 parent ee600c0 commit f8ad168

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

2444.CountSubarrays.cs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// 2444. Count Subarrays With Fixed Bounds
2+
// You are given an integer array nums and two integers minK and maxK.
3+
4+
// A fixed-bound subarray of nums is a subarray that satisfies the following conditions:
5+
6+
// The minimum value in the subarray is equal to minK.
7+
// The maximum value in the subarray is equal to maxK.
8+
// Return the number of fixed-bound subarrays.
9+
// A subarray is a contiguous part of an array.
10+
11+
// Example 1:
12+
// Input: nums = [1,3,5,2,7,5], minK = 1, maxK = 5
13+
// Output: 2
14+
// Explanation: The fixed-bound subarrays are [1,3,5] and [1,3,5,2].
15+
// Example 2:
16+
// Input: nums = [1,1,1,1], minK = 1, maxK = 1
17+
// Output: 10
18+
// Explanation: Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.
19+
20+
// Constraints:
21+
// 2 <= nums.length <= 105
22+
// 1 <= nums[i], minK, maxK <= 106
23+
24+
public class Solution {
25+
//intuition: we need to find the number of subarrays that have minK and maxK as the minimum and maximum values respectively.
26+
//we can keep track of the last index of minK and maxK in the array and the last index of a value that is not in the range of minK and maxK.
27+
//if we find a value that is not in the range of minK and maxK, we update the last index of the value to the current index.
28+
//if we find a value that is equal to minK, we update the last index of minK to the current index.
29+
public long CountSubarrays(int[] nums, int minK, int maxK) {
30+
long result = 0;
31+
long bad_idx, min_idx, max_idx;
32+
bad_idx = min_idx = max_idx = -1;
33+
for(int i = 0; i < nums.Length; i++){
34+
if(nums[i] < minK || nums[i] > maxK)
35+
bad_idx = i;
36+
if(nums[i] == minK)
37+
min_idx = i;
38+
if(nums[i] == maxK)
39+
max_idx = i;
40+
//we add the number of subarrays that have minK and maxK as the minimum and maximum values respectively.
41+
//its the minimum of the last index of minK and maxK minus the last index of a value that is not in the range of minK and maxK.
42+
result += Math.Max(0, Math.Min(min_idx, max_idx) - bad_idx);
43+
}
44+
return result;
45+
}
46+
}

0 commit comments

Comments
 (0)