|
| 1 | +from typing import List |
| 2 | + |
| 3 | +class Solution: |
| 4 | + def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: |
| 5 | + numbers = {} |
| 6 | + size = len(nums) - k + 1 |
| 7 | + answer = [-1] * size |
| 8 | + j = 0 |
| 9 | + |
| 10 | + for i, number in enumerate(nums): |
| 11 | + numbers[number] = numbers.get(number, 0) + 1 |
| 12 | + |
| 13 | + # building while iterating over the list |
| 14 | + # in every loop we need to check if the window is full (k) |
| 15 | + # when the window is full then we extract the first x-sum: |
| 16 | + # |
| 17 | + # filter the numbers that have value (ocurrencies) > x |
| 18 | + # if occurencies are equal then keep only the higher key |
| 19 | + # then sum result of previous operation |
| 20 | + # then add to the res array |
| 21 | + |
| 22 | + if i - k + 1 >= 0: |
| 23 | + # this is the logic required by the problem. We need to get the top |
| 24 | + # elements sorted by the qty then if they draw the bigger number will |
| 25 | + # be selected |
| 26 | + sums = sorted([(v, key) for key, v in numbers.items()], reverse=True) |
| 27 | + # then keep only the X top elements |
| 28 | + answer[j] = sum([pair[0] * pair[1] for pair in sums[:x]]) |
| 29 | + j += 1 |
| 30 | + |
| 31 | + # need to reduce the quantity of the number i - k + 1 positions ago |
| 32 | + numbers[nums[i - k + 1]] -= 1 |
| 33 | + |
| 34 | + return answer |
| 35 | + |
| 36 | +nums = [1,1,2,2,3,4,2,3] |
| 37 | +k = 6 |
| 38 | +x = 2 |
| 39 | + |
| 40 | +nums = [3,8,7,8,7,5] |
| 41 | +k = 2 |
| 42 | +x = 2 |
| 43 | + |
| 44 | +print(Solution().findXSum(nums, k, x)) |
0 commit comments