其他分享
首页 > 其他分享> > 1090. Largest Values From Labels

1090. Largest Values From Labels

作者:互联网

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:

Return the largest possible sum of the subset S.

 

Example 1:

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.

Example 2:

Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2
Output: 12
Explanation: The subset chosen is the first, second, and third item.

Example 3:

Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1
Output: 16
Explanation: The subset chosen is the first and fourth item.

Example 4:

Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2
Output: 24
Explanation: The subset chosen is the first, second, and fourth item.

 

Note:

  1. 1 <= values.length == labels.length <= 20000
  2. 0 <= values[i], labels[i] <= 20000
  3. 1 <= num_wanted, use_limit <= values.length

思路:贪心

class Solution(object):
    def largestValsFromLabels(self, values, labels, num_wanted, use_limit):
        """
        :type values: List[int]
        :type labels: List[int]
        :type num_wanted: int
        :type use_limit: int
        :rtype: int
        """
        vls = [(v,l) for v,l in zip(values,labels)]
        vls.sort(key=lambda a:-a[0])
        
        res=0
        d={}
        i=0
        for _ in range(num_wanted):
            while i<len(vls) and d.get(vls[i][1],0)>=use_limit:
                i+=1
            if i==len(vls): break
            d[vls[i][1]]=d.get(vls[i][1],0)+1
            res+=vls[i][0]
            i+=1
        return res
    

 

标签:use,Labels,1090,labels,limit,num,Values,values,wanted
来源: https://blog.csdn.net/zjucor/article/details/92384215