贪心算法之不找零的金钱最佳组合问题C++

这里写自定义目录标题

问题重述

假设我们传递一个指定的金额数目,假设可以使用给定的货币面值和对应的数量达到金额就打印,并展示使用的货币以及个数,如果无法完成则返回 − 1 -1 1

解决方案

#include "iostream"
#include "map"

/**.
 * 使用贪心算法求解支付指定金额最少需要的面值,及纸币数
 * @param moneyTotal 需要支付的面额总数
 */
int buyFood(int moneyTotal) {
  int moneyArray[] = {1, 2, 5, 10, 20, 50, 100};
  int totalArray[] = {3, 1, 2, 1, 1, 3, 5};

  int total = sizeof(moneyArray) / sizeof(int);

  int currentNeedTotal;

  int resultNeedTotal = 0;

  std::map<int, int> useMoneyMap;

  for (int i = total - 1; i >= 0; --i) {
    if (moneyArray[i] <= moneyTotal) {

      currentNeedTotal = std::min(moneyTotal / moneyArray[i], totalArray[i]);

      useMoneyMap.insert(std::make_pair(moneyArray[i], currentNeedTotal));

      resultNeedTotal += currentNeedTotal;

      moneyTotal -= currentNeedTotal * moneyArray[i];
    }
  }

  if (moneyTotal > 0) {
    resultNeedTotal = -1;
    return resultNeedTotal;
  }

  for (const auto &item: useMoneyMap) {
    // 打印输出
    std::cout << item.first << " : " << item.second << std::endl;
  }

  // 打印输出
  std::cout << std::endl;
  return resultNeedTotal;
}

本帖只做记录学习,关于此算法和问题欢迎大家一起讨论和交流,互相学习

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值