最小硬币问题_进行更改的最小硬币数量

最小硬币问题

Description:

描述:

This is classic dynamic programming problem to find minimum number of coins to make a change. This problem has been featured in interview rounds of Amazon, Morgan Stanley, Paytm, Samsung etc.

这是经典的动态编程问题,用于寻找进行更改的最小硬币数量。 亚马逊,摩根士丹利,Paytm,三星等公司的采访回合都突出了这个问题。

Problem statement:

问题陈述:

Given a value P, you have to make change for P cents, given that you have infinite supply of each of C { C1, C2, ... ,Cn} valued coins. Find the minimum number of coins to make the change. Return -1 if the change is not possible with the coins provided.

给定一个值P ,由于您拥有C {C 1 ,C 2 ,...,C n }个有价硬币的无限供应,因此您必须为P美分进行更改。 找到进行更改的最小硬币数量 。 如果提供的硬币无法找零,请返回-1

    Input:
Amount P=13
Coin values are:
1, 4, 5 
Output:
3

Explanation with example

举例说明

Let's solve the above example. Total amount is 13 and we have coins with values 1, 4 and 5.

让我们解决以上示例。 总金额为13,我们有价值分别为1、4和5的硬币。

Since, we are to find minimum number of coins and we have infinite number of coin for any denomination, it's apparent that we would go for greedy. We should pick the coin with maximum denomination and keep trying with that until the remaining amount of the change is less the denomination of the coin. Then on course we keep choosing the next best one. So, the algorithm would be like.

因为,我们要找到最小数量的硬币,而对于任何面额我们都拥有无限数量的硬币,所以显然我们会贪婪。 我们应该选择面额最大的硬币,并继续尝试直到零钱的剩余金额少于硬币面额为止。 然后,当然我们会继续选择次佳的。 因此,该算法将是这样。

    1) Let, count=0 to count minimum number of coin used
2) Pick up coin with maximum denomination say, value x
3) while amount≥x
amount=amount-x
count=count+1 
4) if amount=0
Go to Step 7
5) Pick up the next best denomination of coin and assign it to x
6) Go to Step 2
7) End. count is the minimum number of coin used.

Let's see whether the above greedy algorithm leads to the desired result or not.

让我们看看上面的贪婪算法是否导致了期望的结果。

    So, we would pick up 5 first from {1, 4, 5}
We would pick 5 two times
Now amount=3, count=2
Next best coin is 4 but 4 > amount
Next best coin is 1
We would pick 1 three times
Amount=0 and count=5
So, minimum number of coins needed for the change is 5.
But is it really minimum?
If we choose one coin with denomination 5 and two coins with denomination 4, 
it would make the change and coins needed here is (2+1) = 3 
So, greedy does not work as the local optimum choices doesn't make 
global optimum choice. Hence, we need dynamic programming.

Problem Solution Approach

问题解决方法

We have amount M and n number of coins, {C1, C2, ..., Cn}

我们有M个n个硬币, {C 1 ,C 2 ,...,C n }

Now,

现在,

We have two choice for any Cj,

对于任何C j ,我们都有两种选择。

  1. Use Cj and recur for amount M-Cj

    使用C j并递归MC j

  2. Don't use Cj and recur for amount M with other coins

    不要使用C j并与其他硬币重现金额M

(m)= minimum number of coins needed to change amount m

(m)=找零数量m所需的最小硬币数量

formula

We can formulate the above recursion using DP.

我们可以使用DP来制定上述递归。

    // (for any amount 0 to M, minimum number of coins needed is initially infinity) 
1) Initialize DP[M+1] with INT_MAX. 
2) DP[0]=0 //base case of above recursion
3)  for  i=1 to M //iterate amounts
for any coin C_j
If i>=C_j  && DP[i-C_j]≠INT_MAX && DP[i-C_j]+1<DP[i])
DP[i]=DP[i-C_j]+1; //update value
End for
End for   
The result is DP[M]

C++ implementation:

C ++实现:

#include <bits/stdc++.h>
using namespace std;
int coin_change(vector<int> a, int m, int n)
{
//recursive implementation//
// if(m<0)
// return;
// if(m==0){
//     if(count<min_count)
//     min_count=count;
//     return;
// }
// for(int i=0;i<n;i++){
//     coin_change(a,i,m-a[i],n,count+1);
//     coin_change(a,i+1,m-a[i],n,count+1);
// }
///DP implementation///
//base value
int DP[m + 1];
//initialize
for (int i = 1; i <= m; i++)
DP[i] = INT_MAX;
DP[0] = 0;
for (int i = 1; i <= m; i++) {
for (int j = 0; j < n; j++) {
// if amount > coin value
if (i >= a[j] && DP[i - a[j]] != INT_MAX && DP[i - a[j]] + 1 < DP[i])
// if updation possible update for minimum value
DP[i] = DP[i - a[j]] + 1;
}
}
return DP[m];
}
int main()
{
int n, item, m;
cout << "Enter amount to be changes:\n";
cin >> m;
cout << "Enter number of coins:\n";
cin >> n;
cout << "Enter coin values\n";
vector<int> a;
for (int j = 0; j < n; j++) {
scanf("%d", &item);
a.push_back(item);
}
int ans = coin_change(a, m, n);
if (ans == INT_MAX)
cout << "Coin change not possible" << endl;
else
cout << "Minimum number of coins needed: " << ans << endl;
return 0;
}

Output

输出量

RUN 1:
Enter amount to be changes:
13
Enter number of coins:
3
Enter coin values
1 4 5
Minimum number of coins needed: 3
RUN 2:
Enter amount to be changes:
11
Enter number of coins:
2
Enter coin values
4 5
Coin change not possible

翻译自: https://www.includehelp.com/icp/minimum-number-of-coins-to-make-the-change.aspx

最小硬币问题

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/541447.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

java 生成xml乱码_jdom解决中文乱码问题 JAVA生成xml文件帮了我很大的忙

决解了数据库读取出来 再保存到xml 产生的乱码问题import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;import org.jdom.Attribute;import org.jdom.Document;import org.jdom.Element;import org.jdom.output.Format;import org.…

给定重量上限,背包问题_满足给定重量的袋子的最低成本

给定重量上限,背包问题Problem statement: 问题陈述&#xff1a; You are given a bag of size W kg and you are provided costs of packets different weights of oranges in array cost[] where cost[i] is basically cost of i kg packet of oranges. cost[i] -1 means t…

springMVC rest风格

1.dispatcherServlet的配置<!-- The front controller of this Spring Web application, responsible for handling all application requests --><servlet><servlet-name>springDispatcherServlet</servlet-name><servlet-class>org.springfram…

sql2008能否打开mysql数据库_mysql数据库数据能不能导入到sql server中

点“测试”按钮确认你的链接是正确的。 Press the "Test" button to ensure your connection settings are set properly and then the "OK" button when youre done.二. 创建Microsoft SQL到MySQL的链接1.在SQL Server Management Studio中打开一个new qu…

c语言 函数的参数传递示例_isunordered()函数与C ++中的示例

c语言 函数的参数传递示例C isunordered()函数 (C isunordered() function) isunordered() function is a library function of cmath header, it is used to check whether the given values are unordered (if one or both values are Not-A-Number (NaN)), then they are u…

java进一_JAVA小白进:基础入门知识

1.注释&#xff0c;关键字&#xff0c;标识符1.注释(1)注释&#xff1a;解释说明程序的而文字。(2)注释的分类&#xff1a;单行注释 格式&#xff1a; //注释的文字多行注释 格式&#xff1a;/*注释的文字*/文档注释 格式&#xff1a;/**注释的文字*/(3)注释的作用&#xff1a;…

补丁(patch)的制作与应用

为什么80%的码农都做不了架构师&#xff1f;>>> 转自http://linux-wiki.cn/wiki/zh-hans/%E8%A1%A5%E4%B8%81(patch)%E7%9A%84%E5%88%B6%E4%BD%9C%E4%B8%8E%E5%BA%94%E7%94%A8 如果hack了开源代码&#xff0c;为了方便分享&#xff08;如提交Bug&#xff09;或自己…

php知识点汇总与解答_PHP操作员能力倾向问题与解答

php知识点汇总与解答This section contains Aptitude Questions and Answers on PHP Operators. 本节包含有关PHP运算符的 Aptitude问答。 1) Which of the following types of operators are used in PHP? Arithmetic OperatorsLogical OperatorsArray OperatorsString Oper…

csv导入mysql phpmyadmin_【转】从phpMyAdmin批量导入Excel内容到MySQL(亲测非常简洁有效)...

今天做项目遇到需要用phpMyAdmin批量导入Excel内容到MySQL数据库。分析了我的踏坑经历并且总结一最便捷的一套导入数据的方法&#xff0c;非常实用简洁&#xff1a;1、修改Excel表的数据&#xff0c;使得Excel中的字段与数据库字段要一一对应&#xff0c;并加上自增id。2、然后…

weakhashmap_Java WeakHashMap putAll()方法与示例

weakhashmapWeakHashMap类的putAll()方法 (WeakHashMap Class putAll() method) putAll() method is available in java.util package. putAll()方法在java.util包中可用。 putAll() method is used to copy all of the associations or mappings from the given map and assig…

c语言memcmp和java的_C语言memcmp()函数:比较m字节长的两个字符串s1和s2

函数名&#xff1a;memcmp头文件&#xff1a;函数原型&#xff1a; void* memcmp(void *s1,void *s2,unsigned m);功能&#xff1a;比较m字节长的两个字符串s1和s2参数&#xff1a; s1 和 s2 为要比较的字符串unsigned m 为要比较的前m个字节返回值&#xff1a;s1s1s2 返回等…

[下载地址] Subclipse 1.10.9(SVN) _附说明

http://pan.baidu.com/s/1bp6EFHt转载于:https://www.cnblogs.com/gscq073240/articles/6814429.html

hbase 伪分布安装 java_HBase基础和伪分布式安装配置

一、HBase(NoSQL)的数据模型1.1 表(table)&#xff0c;是存储管理数据的。1.2 行键(row key)&#xff0c;类似于MySQL中的主键&#xff0c;行键是HBase表天然自带的&#xff0c;创建表时不需要指定1.3 列族(column family)&#xff0c;列的集合。一张表中有多个行健&#xff0c…

java treemap_Java TreeMap firstEntry()方法及示例

java treemapTreeMap类的firstEntry()方法 (TreeMap Class firstEntry() method) firstEntry() method is available in java.util package. firstEntry()方法在java.util包中可用。 firstEntry() method is used to retrieve the key-value pairs linked with the lowest valu…

linux常用网络命令ping和arping

linux常用网络命令ping和arping ping 向目标主机发送icmp请求包 常用来测试当前主机与目标主机网络连接状况 常见选项 -c 设置发包的个数 -s 设置发的包的块大小&#xff0c;最大不超过65507 -W 设置接收回应超时时间 -i …

java printwriter实例_PrintWriter做过滤流+FileWriter案例分析

package com.mstf.ui;import java.io.*;public class TestWriter{public static void main(String args[]){//PrintWriter做过滤流FileWriter//doFilter1();//2、PrintWriter做过滤流OutputStreamWriter//doFilter2();//3、PrintWriter可以作为节点流//doNode();//4、PrintWrit…

treemap比较器_Java TreeMap比较器()方法与示例

treemap比较器TreeMap类的compare()方法 (TreeMap Class comparator() method) comparator() method is available in java.util package. 比较器()方法在java.util包中可用。 comparator() method is used to return the key element in this TreeMap based on the Comparator…

洛谷P1204 [USACO1.2]挤牛奶Milking Cows 前缀和

这题数据比较水 暴搜都能够过去 1 #include <cstdio>2 #include <cmath>3 #include <cstdlib>4 #include <algorithm>5 #include <string>6 #include <iostream>7 #include <iomanip>8 #include <cstring>9 using namespace s…

java script创建对象_JavaScript七种非常经典的创建对象方式

JavaScript创建对象的方式有很多&#xff0c;通过Object构造函数或对象字面量的方式也可以创建单个对象&#xff0c;显然这两种方式会产生大量的重复代码&#xff0c;并不适合量产。接下来介绍七种非常经典的创建对象的方式&#xff0c;他们也各有优缺点。一、工厂模式可以无数…

java 方法 示例_Java扫描仪具有示例的NextNextInt()方法

java 方法 示例扫描器类的hasNextInt()方法 (Scanner Class hasNextInt() method) Syntax: 句法&#xff1a; public boolean hasNextInt();public boolean hasNextInt(int rad);hasNextInt() method is available in java.util package. hasNextInt()方法在java.util包中可用…