aboutsummaryrefslogtreecommitdiff
path: root/count_subarr_max_elem_k.c
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-04-28 18:48:09 -0600
committerJack Sangdahl <[email protected]>2025-04-28 18:48:09 -0600
commit2e8743f0ebda2c02358ce0f124a754fcf9059668 (patch)
treeb337cd80935b671bccc697fab3a6222deb8abac6 /count_subarr_max_elem_k.c
parentc8dfd03864b524280c0c3c745e6a7c428b6bfe5b (diff)
downloadleetcode-2e8743f0ebda2c02358ce0f124a754fcf9059668.tar.gz
leetcode-2e8743f0ebda2c02358ce0f124a754fcf9059668.zip
2962. count subarrays where max element appears at least k times
Diffstat (limited to 'count_subarr_max_elem_k.c')
-rw-r--r--count_subarr_max_elem_k.c20
1 files changed, 8 insertions, 12 deletions
diff --git a/count_subarr_max_elem_k.c b/count_subarr_max_elem_k.c
index e6bf5ad..4768843 100644
--- a/count_subarr_max_elem_k.c
+++ b/count_subarr_max_elem_k.c
@@ -9,19 +9,15 @@
*/
long long countSubarrays(int *nums, int numsSize, int k) {
- int max = 0, cnt = 0, idx[numsSize];
+ int max = -1, curr = 0;
long long ans = 0;
- for (int i = 0; i < numsSize; i++)
- max = max > nums[i];
- for (int i = 0; i < numsSize; i++)
- if (nums[i] == max)
- idx[cnt++] = i;
- for (int i = 0; i <= cnt - k; i++) {
- long long left = idx[i], right = idx[i + k - 1],
- bound = i - 1 >= 0 ? idx[i - 1] : -1;
- if (!i)
- bound = -1;
- ans += (left - bound) * (numsSize - right);
+ for (int i = 0; i < numsSize; ++i)
+ max = nums[i] > max ? nums[i] : max;
+ for (int l = 0, r = 0; r < numsSize; r++) {
+ curr += nums[r] == max;
+ while (curr >= k)
+ curr -= nums[l++] == max;
+ ans += l;
}
return ans;
}