zoukankan      html  css  js  c++  java
  • 【leetcode】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:

    • |S| <= num_wanted
    • For every label L, the number of items in Swith label L is <= use_limit.

    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

    解题思路:贪心算法。每次取values中的最大值,如果对应labels没有超过限制,那么表示最大值可取;否则继续判断次大值。

    代码如下:

    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
            """
            res = 0
            def cmpf(v1,v2):
                if v1[0] - v2[0] != 0:
                    return v2[0] - v1[0]
                return v2[1] - v1[1]
            val_list = sorted(zip(values,labels),cmp=cmpf)
    
            dic = {}
            inx = 0
            while num_wanted > 0 and inx < len(val_list):
                v,l = val_list[inx]
                if l not in dic or dic[l] < use_limit:
                    res += v
                    dic[l] = dic.setdefault(l,0) + 1
                    num_wanted -= 1
                inx += 1
            return res
  • 相关阅读:
    js定位光标到输入框指定位置
    JS获取本机时间和实时动态时间代码
    一个小游戏
    select optionschange oeder
    js控制下拉列表框
    glow滤镜的使用
    body.innerHTML
    怎样用C语言编写病毒(三)
    2011东北地区赛G题(二分网络流判可行性)
    Codeforces Round #122 (Div. 1)>TLE代码 跪求(n^2)的最小割顶集算法(StoerWagner)
  • 原文地址:https://www.cnblogs.com/seyjs/p/11044708.html
Copyright © 2011-2022 走看看