每日一练leetcode

雪糕的最大数量

夏日炎炎,小男孩 Tony 想买一些雪糕消消暑。

商店中新到 n 支雪糕,用长度为 n 的数组 costs 表示雪糕的定价,其中 costs[i] 表示第 i 支雪糕的现金价格。Tony 一共有 coins 现金可以用于消费,他想要买尽可能多的雪糕。

给你价格数组 costs 和现金量 coins ,请你计算并返回 Tony 用 coins 现金能够买到的雪糕的 最大数量 。

class Solution {
    public int maxIceCream(int[] costs, int coins) {
        Arrays.sort(costs);
        if(costs[0]>coins)
            return 0;
            int i = 0;
            int count = 0;
            int n = costs.length;
        while(count < n && coins > 0){
            coins = coins - costs[i];
            if(coins < 0)
                break;
            count = count + 1;
            i++;
        }

        return count;
    }
}

  解法:此题是很经典的贪心算法,不算难题 此题的方法就是排序+贪心

原文地址:https://www.cnblogs.com/nenu/p/15323759.html