Given an array of integers nums and an integer k, find all numbers that appear exactly k times consecutively in the array.
Return the sum of all such numbers. If a number appears in multiple separate consecutive runs of exactly k, count it each time.
Function Signature
def sum_of_consecutive_k(nums: list[int], k: int) -> int:
...
Rules
-
A run is a maximal block of adjacent equal elements, so it cannot be extended on either side.
-
A run counts only when its length is exactly
k
. A longer run does not count and is never split into shorter runs.
-
Each qualifying run adds its value once to the sum. Return
0
when no run qualifies.
Constraints
-
1 <= len(nums) <= 10**5
-
-10**4 <= nums[i] <= 10**4
-
1 <= k <= len(nums)
Examples
Input: nums = [1, 1, 2, 2, 2, 3, 3], k = 2
Output: 4
The runs are [1, 1] (length 2), [2, 2, 2] (length 3) and [3, 3] (length 2). The runs of length exactly 2 hold 1 and 3, and 1 + 3 = 4.
Input: nums = [5, 5, 5, 3, 3, 3, 7], k = 3
Output: 8
The runs are [5, 5, 5], [3, 3, 3] and [7]. The first two have length 3, so the sum is 5 + 3 = 8.
Input: nums = [4, 4, 7, 4, 4, 4, 4, -1, -1, 4, 4], k = 2
Output: 7
The runs have lengths 2 (value 4), 1 (value 7), 4 (value 4), 2 (value -1) and 2 (value 4). The run of four 4s is too long and does not count, while both separate pairs of 4s do, so the sum is 4 + (-1) + 4 = 7.