动态规划--硬币最优

三种硬币,2元、5元、7元,每种硬币足够多,买一本书需要27元,用最少的硬币组合

package com.fenxiangbuy.scm.xdtools.common.utils;

import cn.hutool.core.util.NumberUtil;

/**
 * @Description TODO
 * @Date 2021/3/23 14:23
 * @Created by renchengpeng
 */
public class Test {

    public static void main(String[] args) {
        /**
         * f(x) = 组成x币值需要的最少硬币数量
         * f(x)=min(f(x-2),f(x-5),f(x-7))+1
         *
         * x-2 小于0 =====》-1
         * f(x)无法组成===》-1
         * [0,-1,1,-1,2,1,3,1,4,2,2,3,2,4,2,5,3,3,4,3,5,3,6,4,4,5,4,6]
         */

        Integer[] coinCountArr = new Integer[28];

        coinCountArr[0] = 0;
        for (int coinIndex = 1; coinIndex < coinCountArr.length; coinIndex++) {
            if (coinIndex < 2) {
                coinCountArr[coinIndex] = -1;
            }
            coinCountArr[coinIndex] = getCoinCount(coinCountArr, coinIndex);
        }

        System.out.println(JsonUtil.bean2Json(coinCountArr));
    }

    private static Integer getCoinCount(Integer[] coinCountArr, int coin) {
        Integer count7 = coin >= 7 && coinCountArr[coin - 7] != -1 ? coinCountArr[coin - 7] + 1 : Integer.MAX_VALUE;
        Integer count5 = coin >= 5 && coinCountArr[coin - 5] != -1 ? coinCountArr[coin - 5] + 1 : Integer.MAX_VALUE;
        Integer count2 = coin >= 2 && coinCountArr[coin - 2] != -1 ? coinCountArr[coin - 2] + 1 : Integer.MAX_VALUE;
        Integer min = NumberUtil.min(count2, count5, count7);
        return min.equals(Integer.MAX_VALUE) ? -1 : min;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值