LeetCode 1090. Largest Values From Labels解题报告(python)
1090. Largest Values From Labels
- Largest Values From Labels python solution
题目描述
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: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1
在这里例子中,子集元素的个数<= 3
按照label将子集每个元素列出来
Label 1 -> [5,4]
Label 2 -> [3,2]
Label 3 -> [1]
现在对于每个label的元素我们,至多取一个,因为use_limit = 1
题目要求我们取子集元素和可能的最大值,所以在这个例子中
label 1 : 我们取 5,
label 2: 我们取 3
label 3: 我们取 1
5+3+1=9
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: count=collections.defaultdict(int) pair = sorted(zip(values,labels)) sol=0 while num_wanted and pair: value, label=pair.pop() if count[label]<use_limit: count[label]+=1 num_wanted-=1 sol+=value return sol
Reference
https://leetcode.com/problems/largest-values-from-labels/discuss/312777/Simple-sort-in-python
https://leetcode.com/problems/largest-values-from-labels/discuss/313011/Question-Explanation-and-Simple-Solution-or-Java-or-100
- 点赞
- 收藏
- 分享
- 文章举报
- [Leetcode] 317. Shortest Distance from All Buildings 解题报告
- Leetcode 410. Split Array Largest Sum 划分数组 解题报告
- 【LeetCode】413. Arithmetic Slices 解题报告(Python)
- LeetCode 423. Reconstruct Original Digits from English 解题报告
- 【LeetCode】105. Construct Binary Tree from Preorder and Inorder Traversal 解题报告
- [leetcode]19. Remove Nth Node From End of List@Java解题报告
- 【LeetCode】319. Bulb Switcher 解题报告(Python)
- Leetcode 451 python 解题报告
- 【LeetCode】445. Add Two Numbers II 解题报告(Python)
- [Leetcode] 346. Moving Average from Data Stream 解题报告
- [leetcode] 346. Moving Average from Data Stream 解题报告
- 【LeetCode】733. Flood Fill 解题报告(Python)
- LeetCode82 Remove Duplicates from Sorted List II 解题报告
- leetcode 416 python 解题报告
- Leetcode 349. Intersection of Two Arrays 解题报告 Python Java
- [Leetcode] 423. Reconstruct Original Digits from English 解题报告
- [LeetCode] Remove Duplicates from Sorted Array 解题报告
- 【LeetCode】781. Rabbits in Forest 解题报告(Python)
- 【LeetCode】240. Search a 2D Matrix II 解题报告(Python)
- 【LeetCode】503. Next Greater Element II 解题报告(Python)