Skip to content

Commit 227232d

Browse files
committed
[easy] 3318. Find X-Sum of All K-Long Subarrays I
1 parent 4ef5927 commit 227232d

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

3318.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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))

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
| 2848.py | | |
6969
| 2913.py | | |
7070
| 2932.py | | |
71+
| 3318.py | Array / Sliding Window | <https://leetcode.com/problems/find-x-sum-of-all-k-long-subarrays-i> |
7172
| 414.py | | |
7273
| 496.py | | |
7374
| 56.py | | |

0 commit comments

Comments
 (0)