Leetcode1090. 受标签影响的最大值

思路:根据值从大到小排序,然后在加的时候判断是否达到标签上限即可,一开始想用字典做,但是题目说是集合却连续出现两个8,因此使用元组+SortedList进行解决

python 复制代码
class Solution:
    def largestValsFromLabels(self, values: list[int], labels: list[int], numWanted: int, useLimit: int) -> int:
        from sortedcontainers import SortedList
        from collections import defaultdict
        sorted_values = SortedList()
        for num in range(0, len(labels)):
            sorted_values.add((values[num], labels[num]))
        total_sum = 0
        label_dict = defaultdict(int)
        for value_label in reversed(sorted_values):
            value = value_label[0]
            label = value_label[1]
            if label_dict[label] < useLimit:
                if numWanted > 0:
                    numWanted -= 1
                    total_sum += value
                    label_dict[label] += 1
                else:
                    return total_sum
        return total_sum
相关推荐
databook3 小时前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风4 小时前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风4 小时前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei20 小时前
python 抽象基类
python
用户83562907805121 小时前
Python 实现 PPT 转 HTML
后端·python
zone77391 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77391 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒2 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm
唐叔在学习2 天前
就算没有服务器,我照样能够同步数据
后端·python·程序员
曲幽2 天前
FastAPI流式输出实战与避坑指南:让AI像人一样“边想边说”
python·ai·fastapi·web·stream·chat·async·generator·ollama