Leetcode.1833雪糕的最大数量

Leetcode.1833雪糕的最大数量

题目难度:中等
题目

思路:排序 + 贪心
1、要想充分利用所有钱买到尽可能多的雪糕;
2、想到贪心算法,首先将数组从小到大进行排序,比较当前金额与数组元素;
3、如果当前金额能够买当前costs[i]的雪糕,当前金额coins = coins - costs[i];
4、雪糕个数count = count + 1;

python代码

class Solution(object):
    def maxIceCream(self, costs, coins):
        """
        :type costs: List[int]
        :type coins: int
        :rtype: int
        """
 
        #对数组进行排序
        costs.sort()
        #print(costs)
        #count 计数雪糕个数
        count = 0
        for i in range(0,len(costs)):
        #当前金额是否能买雪糕
            if coins >= costs[i]:
                coins -= costs[i]
                count += 1
            #否则,直接结束,跳出循环
            else:
                break
        return count

Java代码

class Solution {
    public int maxIceCream(int[] costs, int coins) {
//对数组排序,也可直接使用Arrays.sort();
//冒泡排序
        for (int i = 0;i<costs.length;i++)
        {
           for(int j = 1;j<costs.length - i -1;j++)
           {
               if(costs[j+1]<costs[j])
               {
                   int temp = costs[j];
                   costs[j] = costs[j+1];
                   costs[j+1] = temp;
               }
           }
        }
     
        int count = 0;
        for(int k = 0;k<costs.length;k++)
        {
            if(coins >= costs[k])
            {
                coins -= costs[k];
                count += 1;
            }
            else{
                break;
            }
        }
        return count;

    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值