Largest Values From Labels

You can solve this problem by pairing the values and labels, and then sorting them based on the values. Next, you can iterate through the sorted pairs and add the values to the result, making sure not to exceed the numWanted and useLimit constraints. You can use a dictionary to keep track of the count of items for each label that you have already chosen.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
    def largestValsFromLabels(self, values: List[int], labels: List[int], numWanted: int, useLimit: int) -> int:
        # Pairing values with corresponding labels
        paired_values_labels = sorted([(value, label) for value, label in zip(values, labels)], reverse=True)

        # Dictionary to keep track of the number of items chosen for each label
        label_count = {}

        score = 0
        chosen_count = 0

        # Iterate through the sorted pairs
        for value, label in paired_values_labels:
            # Check if the number of items for the label has reached the useLimit or if we have already chosen numWanted items
            if label_count.get(label, 0) < useLimit and chosen_count < numWanted:
                # Add the value to the score
                score += value

                # Increment the count for the label and the number of chosen items
                label_count[label] = label_count.get(label, 0) + 1
                chosen_count += 1

        return score

Explanation:

  • We start by pairing the values with their corresponding labels and then sorting the pairs in descending order based on the values.
  • We then iterate through the sorted pairs, and for each pair, we check if the label count is less than useLimit and if we haven’t yet chosen numWanted items.
  • If both conditions are met, we add the value to the score and update the count for the label and the number of chosen items.
  • Finally, we return the total score.