贪心算法基础题

分发饼干(LeetCode 455)

/**
     * g 胃口
     * s 饼干尺寸
     * @param g
     * @param s
     * @return
     */
    public static int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);
        Arrays.sort(s);
        int count = 0;
        int start = s.length - 1;
        // 遍历孩子的胃口
        for (int i = g.length - 1; i >= 0; i--) {
            if (start >= 0 && s[start] >= g[i]) {
                start--;
                count++;
            }
        }
        return count;
    }

柠檬水找零(LeetCode 860)

/**
     * 如果第一个就大于5 直接false
     * 找钱时优先找大数额的钱,因为最大额度为20,所以找零只有10和5
     * @param bills
     * @return
     */
    public static boolean lemonadeChange(int[] bills) {
        if (bills[0] > 5) {
            return false;
        }
        int cash_5 = 5;
        int cash_10 = 10;
        int num_5 = 1;
        int num_10 = 0;
        int n = bills.length;
        for (int i = 1; i < n; i++) {
            if (bills[i] == cash_5) {
                num_5++;
            }
            else if( bills[i] == cash_10 ) {
                num_10++;
                if (num_5 > 0) {
                    num_5--;
                } else {
                    return false;
                }
            } else {
                if (num_10 > 0 && num_5 > 0) {
                    num_5--;
                    num_10--;
                } else if (num_5 >= 3) {
                    num_5 -= 3;
                } else {
                    return false;
                }
            }
        }
        return true;
    }
  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值