Largest Values From Labels LeetCode solution in Python

1
from collections import defaultdict
2
import heapq
3

4

5
class Solution:
6
def largestValsFromLabels(
7
self, values: list[int], labels: list[int], numWanted: int, useLimit: int
8
) -> int:
9

10
# Add labels and values into the heap
11
heap = [(-value, label) for value, label in zip(values, labels)]
12
heapq.heapify(heap)
13

14
# Initialize the hashmap
15
used = defaultdict(int)
16

17
# Initialize the result
18
res = 0
19

20
# Iterate until we have used a certain number or the heap is empty
21
while numWanted > 0 and heap:
22

23
# Pop a label and its value from the heap
24
value, label = heapq.heappop(heap)
25

26
# If we can use such label
27
if used[label] < useLimit:
28

29
# Add its value to the result
30
res += -value
31

32
# Increment its count in the hashmap
33
used[label] += 1
34

35
# Decrement the number of numbers we still want
36
numWanted -= 1
37

38
return res

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0