diff options
author | Jack Sangdahl <[email protected]> | 2025-04-26 01:27:38 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-04-26 01:27:38 -0600 |
commit | e005e72b441ae5d8f214adaace18a2312f8be2cf (patch) | |
tree | a207c0a2a4b1a0a1f3b142d855301b03e371d127 | |
parent | cb5eca9739f1acc70755952819206e40cd76a078 (diff) | |
download | leetcode-e005e72b441ae5d8f214adaace18a2312f8be2cf.tar.gz leetcode-e005e72b441ae5d8f214adaace18a2312f8be2cf.zip |
2444. count subarrays with fixed bounds
-rw-r--r-- | count_subarr_fixed_bound.c | 19 | ||||
-rw-r--r-- | count_subarr_fixed_bound.py | 8 |
2 files changed, 12 insertions, 15 deletions
diff --git a/count_subarr_fixed_bound.c b/count_subarr_fixed_bound.c index 569fac4..1685be6 100644 --- a/count_subarr_fixed_bound.c +++ b/count_subarr_fixed_bound.c @@ -11,18 +11,15 @@ long long countSubarrays(int *nums, int numsSize, int minK, int maxK) { long long ans = 0; - int last_min = -1, last_max = -1, start = 0; - for (int i = 0; i < numsSize; i++) { - if (nums[i] > maxK || nums[i] < minK) - start = i + 1; - if (nums[i] == maxK) - last_max = i; + int bad = -1, prev_min = -1, prev_max = -1; + for (int i = 0; i < numsSize; ++i) { + if (nums[i] < minK || nums[i] > maxK) + bad = i; if (nums[i] == minK) - last_min = i; - int pos = fmin(last_max, last_min); - if (start > pos) - continue; - ans += pos - start + 1; + prev_min = i; + if (nums[i] == maxK) + prev_max = i; + ans += fmax(0L, fmin(prev_min, prev_max) - bad); } return ans; } diff --git a/count_subarr_fixed_bound.py b/count_subarr_fixed_bound.py index 44fd99c..7409f42 100644 --- a/count_subarr_fixed_bound.py +++ b/count_subarr_fixed_bound.py @@ -17,15 +17,15 @@ class Solution(object): :type maxK: int :rtype: int """ - ans, last_min, last_max, bad = 0, -1, -1, -1 + ans, prev_min, prev_max, bad = 0, -1, -1, -1 for i, a in enumerate(nums): if not minK <= a <= maxK: bad = i if a == minK: - last_min = i + prev_min = i if a == maxK: - last_max = i - ans += max(0, min(last_min, last_max) - bad) + prev_max = i + ans += max(0, min(prev_min, prev_max) - bad) return ans |