Largest Values From Labels Problem
Description
LeetCode Problem 1090.
You are given n item's value and label as two integer arrays values and labels. You are also given two integers numWanted and useLimit.
Your task is to find a subset of items with the maximum sum of their values such that:
- The number of items is at most
numWanted. - The number of items with the same label is at most
useLimit.
Return the maximum sum.
Example 1:
Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], numWanted = 3, useLimit = 1
Output: 9
Explanation:
The subset chosen is the first, third, and fifth items with the sum of values 5 + 3 + 1.
Example 2:
Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], numWanted = 3, useLimit = 2
Output: 12
Explanation:
The subset chosen is the first, second, and third items with the sum of values 5 + 4 + 3.
Example 3:
Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], numWanted = 3, useLimit = 1
Output: 16
Explanation:
The subset chosen is the first and fourth items with the sum of values 9 + 7.
Constraints:
n == values.length == labels.length1 <= n <= 2 * 10^40 <= values[i], labels[i] <= 2 * 10^41 <= numWanted, useLimit <= n
Solution
Approach: Greedy, Largest Values First
Sort the items by value in decreasing order and take them one by one, skipping an item when its label has already been used useLimit times. Stop after numWanted items or at the end of the list. A hash map counts how many items of each label we took.
Why is this optimal? The constraints only limit how many items we take overall and per label, never which ones. If the best answer skipped an item the greedy took, we could swap it in for a smaller item with the same label (or for any smaller item if there is room), and the sum would not go down. So taking the largest allowed value at each step is always safe.
Note that we take at most numWanted items, not exactly numWanted. Values are non-negative, so taking more allowed items never hurts, but when the labels run out we may end with fewer (example 3 only takes 2 items).
Complexity: O(n log n) time for sorting. O(n) space for the sorted order and the label counts.
class Solution:
def largestValsFromLabels(self, values: List[int], labels: List[int], numWanted: int, useLimit: int) -> int:
used = {} # label -> how many items with it we took
ans = taken = 0
for v, label in sorted(zip(values, labels), reverse=True): # biggest values first
if taken == numWanted:
break
if used.get(label, 0) < useLimit:
used[label] = used.get(label, 0) + 1
taken += 1
ans += v
return ans