From a59eaa2eb4b59960af5e33de84465e156cc395c1 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 31 Mar 2024 16:36:42 +0200 Subject: [PATCH] =?UTF-8?q?cs:=20add=20=C2=AB2444.=20Count=20Subarrays=20W?= =?UTF-8?q?ith=20Fixed=20Bounds=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cs/count-subarrays-with-fixed-bounds.cs | 28 +++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 cs/count-subarrays-with-fixed-bounds.cs diff --git a/cs/count-subarrays-with-fixed-bounds.cs b/cs/count-subarrays-with-fixed-bounds.cs new file mode 100644 index 0000000..7a58024 --- /dev/null +++ b/cs/count-subarrays-with-fixed-bounds.cs @@ -0,0 +1,28 @@ +public class Solution { + public long CountSubarrays(int[] nums, int minK, int maxK) { + long count = 0; + var (minIdx, maxIdx) = (-1, -1); + + for (int i = 0, j = 0; j < nums.Length; ++j) { + var x = nums[j]; + + // is not bounded + if (x < minK || x > maxK) { + i = j + 1; + continue; + } + + if (x == minK) { + minIdx = j; + } + + if (x == maxK) { + maxIdx = j; + } + + count += Math.Max(0, Math.Min(minIdx, maxIdx) - i + 1); + } + + return count; + } +}