You are given an integer array transactions representing a stream of transaction amounts, an integer k representing the size of the sliding window, and an integer threshold.
A window of k consecutive transactions is considered anomalous if the average transaction amount within that window is strictly greater than threshold.
Return the number of anomalous windows of size k in transactions.
Function Signature
def count_anomalies(transactions: list[int], k: int, threshold: int) -> int:
Rules
-
Windows are contiguous and overlap. There are
len(transactions) - k + 1
windows, one starting at each index from 0 to
len(transactions) - k
.
-
The comparison is strict: a window whose average equals
threshold
exactly is not anomalous.
-
The average can be fractional (for example 3.5). It is compared as an exact value, without rounding or truncation.
Constraints
-
1 <= len(transactions) <= 10^5
-
1 <= k <= len(transactions)
-
0 <= transactions[i] <= 10^9
-
0 <= threshold <= 10^9
Examples
Input: transactions = [10, 20, 30, 40, 50], k = 3, threshold = 25
Output: 2
The windows of size 3 are [10, 20, 30] with average 20, [20, 30, 40] with average 30, and [30, 40, 50] with average 40. Only the last two are above 25.
Input: transactions = [5, 5, 5, 5, 5], k = 2, threshold = 5
Output: 0
Every window has an average of exactly 5, which is not strictly greater than the threshold, so no window is anomalous.
Input: transactions = [3, 4, 2, 2], k = 2, threshold = 3
Output: 1
The window [3, 4] has average 3.5, which is above 3. The windows [4, 2] and [2, 2] have averages 3 and 2, so they do not count.