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;
}
}