Skip to content

Commit 9fc35d1

Browse files
committed
test: 3321 solution
py
1 parent 4e3b733 commit 9fc35d1

File tree

1 file changed

+67
-1
lines changed

1 file changed

+67
-1
lines changed

problems/problems_3321/solution.py

Lines changed: 67 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,77 @@
1+
from collections import defaultdict
2+
13
import solution
24
from typing import *
5+
from sortedcontainers import SortedList
36

47

58
class Solution(solution.Solution):
69
def solve(self, test_input=None):
710
return self.findXSum(*test_input)
811

912
def findXSum(self, nums: List[int], k: int, x: int) -> List[int]:
10-
pass
13+
cnt = defaultdict(int)
14+
L = SortedList() # 保存 tuple (出现次数,元素值)
15+
R = SortedList()
16+
sum_l = 0 # L 的元素和
17+
18+
def add(val: int) -> None:
19+
if cnt[val] == 0:
20+
return
21+
p = (cnt[val], val)
22+
if L and p > L[0]: # p 比 L 中最小的还大
23+
nonlocal sum_l
24+
sum_l += p[0] * p[1]
25+
L.add(p)
26+
else:
27+
R.add(p)
28+
29+
def remove(val: int) -> None:
30+
if cnt[val] == 0:
31+
return
32+
p = (cnt[val], val)
33+
if p in L:
34+
nonlocal sum_l
35+
sum_l -= p[0] * p[1]
36+
L.remove(p)
37+
else:
38+
R.remove(p)
39+
40+
def l2r() -> None:
41+
nonlocal sum_l
42+
p = L[0]
43+
sum_l -= p[0] * p[1]
44+
L.remove(p)
45+
R.add(p)
46+
47+
def r2l() -> None:
48+
nonlocal sum_l
49+
p = R[-1]
50+
sum_l += p[0] * p[1]
51+
R.remove(p)
52+
L.add(p)
53+
54+
ans = [0] * (len(nums) - k + 1)
55+
for r, in_ in enumerate(nums):
56+
# 添加 in_
57+
remove(in_)
58+
cnt[in_] += 1
59+
add(in_)
60+
61+
l = r + 1 - k
62+
if l < 0:
63+
continue
64+
65+
# 维护大小
66+
while R and len(L) < x:
67+
r2l()
68+
while len(L) > x:
69+
l2r()
70+
ans[l] = sum_l
1171

72+
# 移除 out
73+
out = nums[l]
74+
remove(out)
75+
cnt[out] -= 1
76+
add(out)
77+
return ans

0 commit comments

Comments
 (0)