文巾解题 1833. 雪糕的最大数量

Posted 刘文巾

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了文巾解题 1833. 雪糕的最大数量相关的知识,希望对你有一定的参考价值。

1 题目描述

2 解题思路

2.1 排序+贪心

我们把雪糕的定价从低到高进行排序。然后从低价开始取,直到当前取出来的价格比coins大为止。

class Solution:
    def maxIceCream(self, costs: List[int], coins: int) -> int:
        costs.sort()
#雪糕定价排序
        now_weight=0
#当前取出来的雪糕的总价格
        count=0
#已经取出来的雪糕的数量
        for i in costs:
            now_weight+=i
            if(now_weight<=coins):
                count+=1
        return(count)

2.2 记数排序+贪心

我们建立一个字典,记录每个价格的雪糕的数量

然后也是按照价格从低到高取雪糕

class Solution:
    def maxIceCream(self, costs: List[int], coins: int) -> int:

        unique_list=list(set(costs))
        unique_list.sort()
#不同的雪糕的价格,从低到高排序
        dic={}
        for i in costs:
            if(i not in dic):
                dic[i]=1
            else:
                dic[i]+=1
#不同价格雪糕的数量                
        now_weight=0
#当前取出来的雪糕的总价格
        count=0
#当前取出来的雪糕的数量
        for i in unique_list:
            if(now_weight+i*dic[i]<=coins):
                count+=dic[i]
                now_weight=now_weight+i*dic[i]
            else:
                count+=(coins-now_weight)//i
                now_weight+=(coins-now_weight)//i * i
        return(count)

以上是关于文巾解题 1833. 雪糕的最大数量的主要内容,如果未能解决你的问题,请参考以下文章

1833. 雪糕的最大数量C++

[M贪心] lc1833. 雪糕的最大数量(贪心+水题)

leetcode No1833 雪糕的最大数量

leetcode No1833 雪糕的最大数量

LeetCode:1832判断句子是否为全字母句1833雪糕的最大数量

LeetCode 1833. 雪糕的最大数量 / NC62 平衡二叉树 / NC7:股票(一次交易)/ NC22 合并两个有序的数组