ให้ลิสต์ shows (ชื่อรายการ) และ durations (ระยะเวลา) หา Duration รวมของ Top-K รายการที่ถูกดูมากที่สุด (รวม Duration ต่อ Show)
ตัวอย่าง: shows=["The BGT","Jack jumper","The BGT","Jokers Company","Music magic"], durations=[10,8,10,18,9], k=2 → 38 (Jokers Company:18, The BGT:20)
ขั้นตอน
- รวม Duration ต่อ Show ด้วย Dictionary
- เรียงค่า Duration จากมากไปน้อย
- รวม
kอันแรก
ตัวอย่างโค้ด
from collections import defaultdict
def solve(shows, durations, k):
if not shows or not durations or not k:
return 0
d = defaultdict(int)
for i in range(len(shows)):
d[shows[i]] += durations[i]
l = sorted(d.values(), reverse=True)
return sum(l[:k])
shows = ["The BGT", "Jack jumper", "The BGT", "Jokers Company", "Music magic"]
durations = [10, 8, 10, 18, 9]
k = 2
print(solve(shows, durations, k)) # Output: 38อินพุต
["The BGT", "Jack jumper", "The BGT", "Jokers Company", "Music magic"], [10, 8, 10, 18, 9], 2
เอาต์พุต
38