Similar Problems
Similar Problems not available
Largest Values From Labels - Leetcode Solution
Companies:
LeetCode: Largest Values From Labels Leetcode Solution
Difficulty: Medium
Topics: greedy hash-table sorting array
Problem statement:
We have a set of items: the i-th item has value values[i] and label labels[i].
Then, we choose a subset S of these items, such that:
|S| <= num_wanted. For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.
Example:
Input: values = [5,4,3,2,1] labels = [1,1,2,2,3] num_wanted = 3 use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item.
Solution:
This problem can be solved in O(n*log(n)) time using the greedy approach. We will sort the items in decreasing order of value and then iterate over them, adding the items to our subset S if they satisfy the label constraints. We keep track of the number of items with each label in S and stop adding items to S for a particular label when we reach the use limit for that label. We stop when we have added num_wanted items to S or there are no more items left.
Step-by-step Algorithm:
- Create a list called items of tuples where each tuple contains the value and label of an item.
- Sort the items in descending order of value.
- Create a dictionary called used_labels to keep track of the number of items we have added to S for each label.
- Initialize the variable ans to 0.
- Iterate over the items in the order defined.
- If the number of items with the label of the current item in S is less than the use limit, add the current item's value to ans and increment the count of the label in used_labels.
- Stop iterating when we have added num_wanted items to S or there are no more items left.
- Return the value of ans.
Pseudo-code:
- items = [(values[i], labels[i]) for i in range(len(values))]
- items.sort(reverse=True)
- used_labels = {}
- ans = 0
- for value, label in items:
- if label in used_labels and used_labels[label] >= use_limit:
-
continue
- ans += value
- used_labels[label] = used_labels.get(label, 0) + 1
- if len(used_labels) == num_wanted:
- break
- return ans
Time Complexity:
The time complexity of the above algorithm is O(nlog(n)), where n is the number of items. The sort function in Python has a time complexity of O(nlog(n)), and iterating over n items has a time complexity of O(n). Therefore, the overall time complexity of the algorithm is O(n*log(n)).
Space Complexity:
The space complexity of the algorithm is O(n) because we are using a dictionary to keep track of the number of items with each label. This dictionary has a maximum size of n, assuming there are n unique labels. We are also storing the items as tuples in a list, which has size n. Therefore, the overall space complexity is O(n).
Largest Values From Labels Solution Code
1