LeetCode solutions

1169. Largest Values From Labels

My accepted Python solution to LeetCode problem 1169, Largest Values From Labels, running in 14ms.

  • Difficulty: Medium
  • Python
  • Runtime 14ms
  • Memory 22.5MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 14ms, memory 22.5MB, accepted 2026-01-02.

python
class Solution:
    def largestValsFromLabels(self, values: List[int], labels: List[int], numWanted: int, useLimit: int) -> int:
        # Pair values with labels and sort by value descending
        items = sorted(zip(values, labels), reverse=True)
        
        label_count = {}
        result = 0
        count = 0
        
        for value, label in items:
            if count >= numWanted:
                break
            
            # Check if we can use this label
            if label_count.get(label, 0) < useLimit:
                result += value
                label_count[label] = label_count.get(label, 0) + 1
                count += 1
        
        return result

Source